Search Results

Search found 1765 results on 71 pages for 'sorting'.

Page 4/71 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Sorting 1000-2000 elements with many cache misses

    - by Soylent Graham
    I have an array of 1000-2000 elements which are pointers to objects. I want to keep my array sorted and obviously I want to do this as quick as possible. They are sorted by a member and not allocated contiguously so assume a cache miss whenever I access the sort-by member. Currently I'm sorting on-demand rather than on-add, but because of the cache misses and [presumably] non-inlining of the member access the inner loop of my quick sort is slow. I'm doing tests and trying things now, (and see what the actual bottleneck is) but can anyone recommend a good alternative to speeding this up? Should I do an insert-sort instead of quicksorting on-demand, or should I try and change my model to make the elements contigious and reduce cache misses? OR, is there a sort algorithm I've not come accross which is good for data that is going to cache miss?

    Read the article

  • haskell sorting

    - by snorlaks
    Hello, How can it be done in most simply way to write (or maybe there is something embedded in haskell) function which takse as arguments list of tuples (String, Int) and Int x and return top x tuples as list according to x value. I wonder if its possible to write a function which also takes 3 argument which is the name of (or index) of filed in tuple according to which sorting has to be done. What are best solutions to make it quite generic, Im new to haskell I would do somethink like that in imperative languages without any problems but I want to know how to write it in quite good way in haskell, thanks for help

    Read the article

  • Sorting an NSArray of NSString

    - by Robert Eisinger
    Can someone please show me the code for sorting an NSMutableArray? I have the following NSMutableArray: NSMutableArray *arr = [[NSMutableArray alloc] init]; with elements such as "2", "4", "5", "1", "9", etc which are all NSString. I'd like to sort the list in descending order so that the largest valued integer is highest in the list (index 0). I tried the following: [arr sortUsingSelector:@selector(compare:)]; but it did not seem to sort my values properly. Can someone show me code for properly doing what I am trying to accomplish? Thanks!

    Read the article

  • Prevent initial array from sorting

    - by George
    I have an array where the order of the objects is important for when I finally output the array in a document. However, I'm also sorting the array in a function to find the highest value. The problem is that I after I run the function to find the highest value, I can't get the original sort order of the array back. // html document var data = [75,300,150,500,200]; createGraph(data); // js document function createGraph(data) { var maxRange = getDataRange(data); // simpleEncode() = google encoding function for graph var dataSet = simpleEncode(data,maxRange); } function getDataRange(dataArray) { var num = dataArray.sort(sortNumber); return num[0]; } I've also tried setting data to dataA and dataB and using dataB in the getDataRange function and dataA in the simpleEncode function. Either way, data always end up being sorted from highest to lowest.

    Read the article

  • Solr alphabetical sorting trouble. Sorting uppercase then lowercase for string type field

    - by Alauddin Ansari
    I've crated a title field with list below: Asking is good But answering is best join the group like this You are the best hey dudes. whass up When I'm sorting this ASC (&sort=title ASC) Asking is good But answering is best You are the best hey dudes. whass up join the group like this and (&sort=title DESC) join the group like this hey dudes. whass up You are the best But answering is best Asking is good But I'm expecting result like: (&sort=title ASC) Asking is good But answering is best hey dudes. whass up join the group like this You are the best schema.xml <field name="title" type="text_general" indexed="true" stored="true"/> <field name="title_sort" type="string" indexed="true" stored="false"/> <copyField source="title" dest="title_sort" /> I'm using title_sort field to sort (also tried title field) Please tell me where I'm going wrong

    Read the article

  • Objective-C : Sorting NSMutableArray containing NSMutableArrays

    - by Dough
    Hi ! I'm currently using NSMutableArrays in my developments to store some data taken from an HTTP Servlet. Everything is fine since now I have to sort what is in my array. This is what I do : NSMutableArray *array = [[NSMutableArray arrayWithObjects:nil] retain]; [array addObject:[NSArray arrayWithObjects: "Label 1", 1, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 2", 4, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 3", 2, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 4", 6, nil]]; [array addObject:[NSArray arrayWithObjects: "Label 5", 0, nil]]; First column contain a Label and 2nd one is a score I want the array to be sorted descending. Is the way I am storing my data a good one ? Is there a better way to do this than using NSMutableArrays in NSMutableArray ? I'm new to iPhone dev, I've seen some code about sorting but didn't feel good with that. Thanks in advance for your answers !

    Read the article

  • help with grouping and sorting for TreeView in xaml

    - by danhotb
    I am having problems getting my head around grouping and sorting in xaml and hope someone can get me straightened out! I have creaed an xml file from a tree of files and folders (just like windows explorer) that can be serveral levels deep. I have bound a TreeView control to an xml datasource and it works great! It sorts everything alphabetically but ... I would like it to sort all folders first then all files, rather than folders listed with files, as it does now. the xml : if you load this to a treeviw it will display the two files before the folder because they are first in alpha-order. here is my code: <!-- This will contain the XML-data. --> <XmlDataProvider x:Key="xmlDP" XPath="*"> <x:XData> <Select_Project /> </x:XData> </XmlDataProvider> <!-- This HierarchicalDataTemplate will visualize all XML-nodes --> <HierarchicalDataTemplate DataType="project" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="folder" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="file" ItemsSource ="{Binding}"> <TextBlock Text="{Binding XPath=@name}" /> </HierarchicalDataTemplate> <CollectionViewSource x:Key="projectView" Source="{StaticResource xmlDP}"> <CollectionViewSource.SortDescriptions> <!-- ADD SORT DESCRIPTION HERE --> </CollectionViewSource.SortDescriptions> </CollectionViewSource> <TreeView Margin="11,79.992,18,19.089" Name="tvProject" BorderThickness="1" FontSize="12" FontFamily="Verdana"> <TreeViewItem ItemsSource="{Binding Source={StaticResource xmlDP}, XPath=*}" Header="Project"/> </TreeView>

    Read the article

  • Sorting arrays with cyclic compares (infinite loop?)

    - by Tiago
    Hi, I have some objects that have 3 sorting options: quality, quatity and a compare against the other object, sorted by that order. - (NSComparisonResult) compare: (MyObject *) obj { if (self.quality > obj.quality) return NSOrderedAscending; else if (self.quality < obj.quality) return NSOrderedDescending; if (self.quantity > obj.quantity) return NSOrderedAscending; else if (self.quantity < obj.quantity) return NSOrderedDescending; if ([self betterThan: obj]) return NSOrderedAscending; if ([obj betterThan: self]) return NSOrderedDescending; return NSOrderedSame; } My problem is that, the betterThan: method might cause a cyclic compare if the objects have the same quality and quantity, and I want to return any sort order in that case. For example, A, B and C have the same quality/quantity, but A betterThan: B => YES B betterThan: C => YES C betterThan: A => YES Solutions? Thanks.

    Read the article

  • Why aren't my objects sorting with sortedArrayUsingDescriptors?

    - by clozach
    I expected the code below to return the objects in imageSet as a sorted array. Instead, there's no difference in the ordering before and after. NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"imageID" ascending:YES]; NSSet *imageSet = collection.images; for (CBImage *image in imageSet) { NSLog(@"imageID in Set: %@",image.imageID); } NSArray *imageArray = [[imageSet allObjects] sortedArrayUsingDescriptors:(descriptor, nil)]; [descriptor release]; for (CBImage *image in imageArray) { NSLog(@"imageID in Array: %@",image.imageID); } Fwiw, CBImage is defined in my core data model. I don't know why sorting on managed objects would work any differently than on "regular" objects, but maybe it matters. As proof that @"imageID" should work as the key for the descriptor, here's what the two log loops above output for one of the sets I'm iterating through: 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360339 2010-05-05 00:49:52.876 Cover Browser[38678:207] imageID in Array: 360337 2010-05-05 00:49:52.877 Cover Browser[38678:207] imageID in Array: 360338 2010-05-05 00:49:52.878 Cover Browser[38678:207] imageID in Array: 360336 2010-05-05 00:49:52.879 Cover Browser[38678:207] imageID in Array: 360335 ... For extra credit, I'd love to get a general solution to troubleshooting NSSortDescriptor troubles (esp. if it also applies to troubleshooting NSPredicate). The functionality of these things seems totally opaque to me and consequently debugging takes forever.

    Read the article

  • MVC Paging and Sorting Patterns: How to Page or Sort Re-Using Form Criteria

    - by CRice
    What is the best ASP.NET MVC pattern for paging data when the data is filtered by form criteria? This question is similar to: http://stackoverflow.com/questions/1425000/preserve-data-in-net-mvc but surely there is a better answer? Currently, when I click the search button this action is called: [AcceptVerbs(HttpVerbs.Post)] public ActionResult Search(MemberSearchForm formSp, int? pageIndex, string sortExpression) {} That is perfect for the initial display of the results in the table. But I want to have page number links or sort expression links re-post the current form data (the user entered it the first time - persisted because it is returned as viewdata), along with extra route params 'pageIndex' or 'sortExpression', Can an ActionLink or RouteLink (which I would use for page numbers) post the form to the url they specify? <%= Html.RouteLink("page 2", "MemberSearch", new { pageIndex = 1 })%> At the moment they just do a basic redirect and do not post the form values so the search page loads fresh. In regular old web forms I used to persist the search params (MemberSearchForm) in the ViewState and have a GridView paging or sorting event reuse it.

    Read the article

  • Problem with sorting NSDictionary

    - by Stas Dmitrenko
    Hello. I need to sort a NSDictionary of dictionaries. It looks like: {//dictionary RU = "110.1"; //key and value SG = "150.2"; //key and value US = "50.3"; //key and value } Result need to be like: {//dictionary SG = "150.2"; //key and value RU = "110.1"; //key and value US = "50.3"; //key and value } I am trying this: @implementation NSMutableDictionary (sorting) -(NSMutableDictionary*)sortDictionary { NSArray *allKeys = [self allKeys]; NSMutableArray *allValues = [NSMutableArray array]; NSMutableArray *sortValues= [NSMutableArray array]; NSMutableArray *sortKeys= [NSMutableArray array]; for(int i=0;i<[[self allValues] count];i++) { [allValues addObject:[NSNumber numberWithFloat:[[[self allValues] objectAtIndex:i] floatValue]]]; } [sortValues addObjectsFromArray:allValues]; [sortKeys addObjectsFromArray:[self allKeys]]; [sortValues sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"floatValue" ascending:NO] autorelease]]]; for(int i=0;i<[sortValues count];i++) { [sortKeys replaceObjectAtIndex:i withObject:[allKeys objectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]]]]; [allValues replaceObjectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]] withObject:[NSNull null]]; } NSLog(@"%@", sortKeys); NSLog(@"%@", sortValues); NSLog(@"%@", [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]); return [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]; } @end This is the result of NSLog: 1) { SG, RU, US } 2) { 150.2, 110.1, 50.3 } 3) { RU = "110.1"; SG = "150.2"; US = "50.3"; } Why is this happening? Can you help me with this problem?

    Read the article

  • L10N: Trusted test data for Locale Specific Sorting

    - by Chris Betti
    I'm working on an internationalized database application that supports multiple locales in a single instance. When international users sort data in the applications built on top of the database, the database theoretically sorts the data using a collation appropriate to the locale associated with the data the user is viewing. I'm trying to find sorted lists of words that meet two criteria: the sorted order follows the collation rules for the locale the words listed will allow me to exercise most / all of the specific collation rules for the locale I'm having trouble finding such trusted test data. Are such sort-testing datasets currently available, and if so, what / where are they? "words.en.txt" is an example text file containing American English text: Andrew Brian Chris Zachary I am planning on loading the list of words into my database in randomized order, and checking to see if sorting the list conforms to the original input. Because I am not fluent in any language other than English, I do not know how to create sample datasets like the following sample one in French (call it "words.fr.txt"): cote côte coté côté The French prefer diacritical marks to be ordered right to left. If you sorted that using code-point order, it likely comes out like this (which is an incorrect collation): cote coté côte côté Thank you for the help, Chris

    Read the article

  • PHP Function needed for GENERIC sorting of a recordset array

    - by donbriggs
    Somebody must have come up with a solution for this by now. I wrote a PHP class to display a recordset as an HTML table/datagrid, and I wish to expand it so that we can sort the datagrid by whichever column the user selects. In the below example data, we may need to sort the recordset array by Name, Shirt, Assign, or Age fields. I will take care of the display part, I just need help with sorting the data array. As usual, I query a database to get a result, iterate throught he result, and put the records into an assciateiave array. So, we end up with an array of arrays. (See below.) I need to be able to sort by any column in the dataset. However, I will not know the column names at design time, nor will I know if the colums will be string or numeric values. I have seen a ton of solutions to this, but I have not seen a GOOD and GENERIC solution Can somebody please suggest a way that I can sort the recordset array that is GENERIC, and will work on any recordset? Again, I will not know the fields names or datatypes at design time. The array presented below is ONLY an example. Array ( [0] = Array ( [name] = Kirk [shrit] = Gold [assign] = Bridge ) [1] => Array ( [name] => Spock [shrit] => Blue [assign] => Bridge ) [2] => Array ( [name] => Uhura [shrit] => Red [assign] => Bridge ) [3] => Array ( [name] => Scotty [shrit] => Red [assign] => Engineering ) [4] => Array ( [name] => McCoy [shrit] => Blue [assign] => Sick Bay ) )

    Read the article

  • Randomly sorting an array

    - by Cam
    Does there exist an algorithm which, given an ordered list of symbols {a1, a2, a3, ..., ak}, produces in O(n) time a new list of the same symbols in a random order without bias? "Without bias" means the probability that any symbol s will end up in some position p in the list is 1/k. Assume it is possible to generate a non-biased integer from 1-k inclusive in O(1) time. Also assume that O(1) element access/mutation is possible, and that it is possible to create a new list of size k in O(k) time. In particular, I would be interested in a 'generative' algorithm. That is, I would be interested in an algorithm that has O(1) initial overhead, and then produces a new element for each slot in the list, taking O(1) time per slot. If no solution exists to the problem as described, I would still like to know about solutions that do not meet my constraints in one or more of the following ways (and/or in other ways if necessary): the time complexity is worse than O(n). the algorithm is biased with regards to the final positions of the symbols. the algorithm is not generative. I should add that this problem appears to be the same as the problem of randomly sorting the integers from 1-k, since we can sort the list of integers from 1-k and then for each integer i in the new list, we can produce the symbol ai.

    Read the article

  • Interview Q: sorting an almost sorted array (elements misplaced by no more than k)

    - by polygenelubricants
    I was asked this interview question recently: You're given an array that is almost sorted, in that each of the N elements may be misplaced by no more than k positions from the correct sorted order. Find a space-and-time efficient algorithm to sort the array. I have an O(N log k) solution as follows. Let's denote arr[0..n) to mean the elements of the array from index 0 (inclusive) to N (exclusive). Sort arr[0..2k) Now we know that arr[0..k) are in their final sorted positions... ...but arr[k..2k) may still be misplaced by k! Sort arr[k..3k) Now we know that arr[k..2k) are in their final sorted positions... ...but arr[2k..3k) may still be misplaced by k Sort arr[2k..4k) .... Until you sort arr[ik..N), then you're done! This final step may be cheaper than the other steps when you have less than 2k elements left In each step, you sort at most 2k elements in O(k log k), putting at least k elements in their final sorted positions at the end of each step. There are O(N/k) steps, so the overall complexity is O(N log k). My questions are: Is O(N log k) optimal? Can this be improved upon? Can you do this without (partially) re-sorting the same elements?

    Read the article

  • custom sorting or ordering a table without resorting the whole shebang

    - by fuugus
    for ten years we've been using the same custom sorting on our tables, i'm wondering if there is another solution which involves fewer updates, especially since today we'd like to have a replication/publication date and would'nt like to have our replication replicate unnecessary entries. i had a look into nested sets, but it does'nt seem to do the job for us. base table: id | a_sort ---+------- 1 10 2 20 3 30 after inserting insert into table (a_sort) values(15) an entry at the second position. id | a_sort ---+------- 1 10 2 20 3 30 4 15 ordering the table with select * from table order by a_sort and resorting all the a_sort entries, updating at least id=(2,3,4) will of course produce the desired output id | a_sort ---+------- 1 10 4 20 2 30 3 40 the column names, the column count, datatypes, a possible join, possible triggers or the way the resorting is done is/are irrelevant to the problem. also we've found some pretty neat ways to do this task fast. only; how the heck can we reduce the updates in the db to 1 or 2 max. seems like an awfully common problem. the captain obvious in me thougth once "use an a_sort float(53), insert using a fixed value of ordervaluefirstentry+abs(ordervaluefirstentry-ordervaluenextentry)/2".. but this would only allow around 1040 "in between" entries - so never resorting seems a bit problematic ;)

    Read the article

  • Sorting a very large text file in Java

    - by Alice
    Hi, I have a large text file I need to sort in Java. The format is: word [tab] frequency [new line] The algorithm for sorting is: Read some of the file, filtering for purlely alphabetic words. Once you have X number of alphabetic words, call Collections.sort and write the result to a file. Repeat until you have finished reading the file. Start reading two sorted files, comparing line by line for the word with higher frequency, and writing at the same time to a new file as to not load much into your memory Repeat until all files are merged into one large file Right now I've divided the large file into smaller ones (sorted by descending frequency) with 10,000 lines each. I know I need to somehow merge these files back together, but I'm not sure how to go about this. I've created a LinkedList to keep track of all the files created. The algorithm says to compare each line in the two files, except I've tried a case where , say file1 = 8,6,5,3,1 and file2 = 9,8,8,8,8. Then if I compare them line by line I would get file3 = 9,8,8,6,8,5,8,3,8,1 which is incorrectly sorted (they should be in decreasing order). I think I'm misunderstanding some part of the algorithm. If someone could point out what I should do instead, I'd greatly appreciate it. Thanks. edit: Yes this is an assignment. We aren't allowed to increase memory unfortunately :(

    Read the article

  • LINQ Sorting - First three need to be different manufacturers

    - by Rob
    My OM has a 'product' object. Each product has a 'manufacturer id' (property, integer). When I have a list of products to display, the first three are displayed as the 'featured products'. The list is already sorted in a specific sort order, putting the 'featured' products first in the list. However, I now need to ensure the featured products in the listing are from different Manufacturers. I want to have a method to call to do this re-sorting. Trying to utilize LINQ to to the querying of the input 'products' and the 'results' public List<Product> SetFeatures(List<Product> products, int numberOfFeatures) { List<Product> result; // ensure the 2nd product is different manufacturer than the first .... // ensure the 3rd product is a different manufacturer than the first two... // ... etc ... for the numberOfFeatures return result; } Thanks in advance.

    Read the article

  • Writing a recursive sorting algorithm of an array of integers

    - by 12345
    I am trying to write a recursive sorting algorithm for an array of integers. The following codes prints to the console: 3, 5, 2, 1, 1, 2, 6, 7, 8, 10, 20 The output should be sorted but somehow "it doesn't work". public static void main(String[] args) { int[] unsortedList = {20, 3, 1, 2, 1, 2, 6, 8, 10, 5, 7}; duplexSelectionSort(unsortedList, 0, unsortedList.length-1); for (int i = 0; i < unsortedList.length; i++) { System.out.println(unsortedList[i]); } } public static void duplexSelectionSort( int[] unsortedNumbers, int startIndex, int stopIndex) { int minimumIndex = 0; int maximumIndex = 0; if (startIndex < stopIndex) { int index = 0; while (index <= stopIndex) { if (unsortedNumbers[index] < unsortedNumbers[minimumIndex]) { minimumIndex = index; } if (unsortedNumbers[index] > unsortedNumbers[maximumIndex]) { maximumIndex = index; } index++; } swapEdges(unsortedNumbers, startIndex, stopIndex, minimumIndex, maximumIndex); duplexSelectionSort(unsortedNumbers, startIndex + 1, stopIndex - 1); } } public static void swapEdges( int[] listOfIntegers, int startIndex, int stopIndex, int minimumIndex, int maximumIndex) { if ((minimumIndex == stopIndex) && (maximumIndex == startIndex)) { swap(listOfIntegers, startIndex, stopIndex); } else { if (maximumIndex == startIndex) { swap(listOfIntegers, maximumIndex, stopIndex); swap(listOfIntegers, minimumIndex, startIndex); } else { swap(listOfIntegers, minimumIndex, startIndex); swap(listOfIntegers, maximumIndex, stopIndex); } } } public static void swap(int[] listOfIntegers, int index1, int index2) { int savedElementAtIndex1 = listOfIntegers[index1]; listOfIntegers[index1] = listOfIntegers[index2]; listOfIntegers[index2] = savedElementAtIndex1; }

    Read the article

  • Sorting a nodeset before passing to xsl:for-each

    - by Zack Mulgrew
    I have a situation where loop through a sorted nodeset and apply a template on each of the nodes: <div id="contractscontainer"> <xsl:for-each select="document"> <xsl:sort select="content[@name='ClientName']/text()" /> <xsl:apply-templates select="." mode="client-contract" /> </xsl:for-each> </div> I want to do something special with the "first" 5 nodes in the node set and render them nested element. The problem is that they need to be in the same order as if they were sorted (as they are in the loop). I had planned on doing this by using two xsl:for-each elements, each with the correct nodes selected from the set. I can't do this, however, because they need to be sorted before I can select the "first" 5. Example: <div id="contractscontainer"> <div class="first-five"> <xsl:for-each select="document[position() < 6]"> <xsl:sort select="content[@name='ClientName']/text()" /> <xsl:apply-templates select="." mode="client-contract" /> </xsl:for-each> </div> <div class="rest-of-them"> <xsl:for-each select="document[position() > 5]"> <xsl:sort select="content[@name='ClientName']/text()" /> <xsl:apply-templates select="." mode="client-contract" /> </xsl:for-each> </div> </div> I don't think this will work because I'm selecting the nodes by position before sorting them, but I can't use xsl:sort outside of the xsl:for-each. Am I approaching this incorrectly?

    Read the article

  • Array Sorting Question for News System

    - by lemonpole
    Hello all. I'm currently stuck trying to figure out how to sort my array files. I have a simple news posting system that stores the content in seperate .dat files and then stores them in an array. I numbered the files so that my array can sort them from lowest number to greatest; however, I have run into a small problem. To begin here is some more information on my system so that you can understand it better. The function that gathers my files is: function getNewsList() { $fileList = array(); // Open the actual directory if($handle = opendir(ABSPATH . ADMIN . "data")) { // Read all file from the actual directory while($file = readdir($handle)) { if(!is_dir($file)) { $fileList[] = $file; } } } // Return the array. return $fileList; } On a seperate file is the programming that processes the news post. I didn't post that code for simplicity's sake but I will explain how the files are named. The files are numbered and the part of the post's title is used... for the numbering I get a count of the array and add "1" as an offset. I get the title of the post, encode it to make it file-name-friendly and limit the amount of text so by the end of it all I end up with: // Make the variable that names the file that will contain // the post. $filename = "00{$newnumrows}_{$snipEncode}"; When running print_r on the above function I get: Array ( [0] => 0010_Mira_mi_Soledad.dat [1] => 0011_WOah.dat [2] => 0012_Sinep.dat [3] => 0013_Living_in_Warfa.dat [4] => 0014_Hello.dat [5] => 001_AS.dat [6] => 002_ASASA.dat [7] => 003_SSASAS.dat ... [13] => 009_ASADADASADAFDAF.dat ) And this is how my content is displayed. For some reason according to the array sorting 0010 comes before 001...? Is there a way I can get my array to sort 001 before 0010?

    Read the article

  • Sorting a file with 55K rows and varying Columns

    - by Prasad
    Hi I want to find a programmatic solution using C++. I have a 900 files each of 27MB size. (just to inform about the enormity ). Each file has 55K rows and Varying columns. But the header indicates the columns I want to sort the rows in an order w.r.t to a Column Value. I wrote the sorting algorithm for this (definitely my newbie attempts, you may say). This algorithm is working for few numbers, but fails for larger numbers. Here is the code for the same: basic functions I defined to use inside the main code: int getNumberOfColumns(const string& aline) { int ncols=0; istringstream ss(aline); string s1; while(ss>>s1) ncols++; return ncols; } vector<string> getWordsFromSentence(const string& aline) { vector<string>words; istringstream ss(aline); string tstr; while(ss>>tstr) words.push_back(tstr); return words; } bool findColumnName(vector<string> vs, const string& colName) { vector<string>::iterator it = find(vs.begin(), vs.end(), colName); if ( it != vs.end()) return true; else return false; } int getIndexForColumnName(vector<string> vs, const string& colName) { if ( !findColumnName(vs,colName) ) return -1; else { vector<string>::iterator it = find(vs.begin(), vs.end(), colName); return it - vs.begin(); } } ////////// I like the Recurssive functions - I tried to create a recursive function ///here. This worked for small values , say 20 rows. But for 55K - core dumps void sort2D(vector<string>vn, vector<string> &srt, int columnIndex) { vector<double> pVals; for ( int i = 0; i < vn.size(); i++) { vector<string>meancols = getWordsFromSentence(vn[i]); pVals.push_back(stringToDouble(meancols[columnIndex])); } srt.push_back(vn[max_element(pVals.begin(), pVals.end())-pVals.begin()]); if (vn.size() > 1 ) { vn.erase(vn.begin()+(max_element(pVals.begin(), pVals.end())-pVals.begin()) ); vector<string> vn2 = vn; //cout<<srt[srt.size() -1 ]<<endl; sort2D(vn2 , srt, columnIndex); } } Now the main code: for ( int i = 0; i < TissueNames.size() -1; i++) { for ( int j = i+1; j < TissueNames.size(); j++) { //string fname = path+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt"; //string fname2 = sortpath2+"/gse7307_Female_rma"+TissueNames[i]+"_"+TissueNames[j]+"Sorted.txt"; string fname = path+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+".txt"; string fname2 = sortpath2+"/gse7307_Male_rma"+TissueNames[i]+"_"+TissueNames[j]+"4Columns.txt"; //vector<string>AllLinesInFile; BioInputStream fin(fname); string aline; getline(fin,aline); replace (aline.begin(), aline.end(), '"',' '); string headerline = aline; vector<string> header = getWordsFromSentence(aline); int pindex = getIndexForColumnName(header,"p-raw"); int xcindex = getIndexForColumnName(header,"xC"); int xeindex = getIndexForColumnName(header,"xE"); int prbindex = getIndexForColumnName(header,"X"); string newheaderline = "X\txC\txE\tp-raw"; BioOutputStream fsrt(fname2); fsrt<<newheaderline<<endl; int newpindex=3; while ( getline(fin, aline) ){ replace (aline.begin(), aline.end(), '"',' '); istringstream ss2(aline); string tstr; ss2>>tstr; tstr = ss2.str().substr(tstr.length()+1); vector<string> words = getWordsFromSentence(tstr); string values = words[prbindex]+"\t"+words[xcindex]+"\t"+words[xeindex]+"\t"+words[pindex]; AllLinesInFile.push_back(values); } vector<string>SortedLines; sort2D(AllLinesInFile, SortedLines,newpindex); for ( int si = 0; si < SortedLines.size(); si++) fsrt<<SortedLines[si]<<endl; cout<<"["<<i<<","<<j<<"] = "<<SortedLines.size()<<endl; } } can some one suggest me a better way of doing this? why it is failing for larger values. ? The primary function of interest for this query is Sort2D function. thanks for the time and patience. prasad.

    Read the article

  • Sorting linked lists in Pascal

    - by user3712174
    I'm doing my final project for Informatics class and I can't get my sorting procedure to work. Have a look at my program, specifically the bolded part (some things are in Croatian. - if you need something translated, let me know): type pokazivac=^slog; slog=record prezime_ime:string[30]; redni_broj:string[2]; fakultet:string[50]; bodovi:integer; sljedeci:pokazivac; end; var pocetni, trenutni, prethodni:pokazivac; i:integer; procedure racunaj; var i,a,c:integer; b,d,e,f,g,h,j:real; begin write('Postotak bodova (u decimalnom zapisu) koje ucenik ostvaruje na temelju prosjeka ocjena - '); readln(e); e:=e*1000/4; write('Prosjek ocjena u prvom razredu : '); readln(f); f:=f/5*e; write('Prosjek ocjena u drugom razredu : '); readln(g); g:=g/5*e; write('Prosjek ocjena u trecem razredu : '); readln(h); h:=h/5*e; write('Prosjek ocjena u cetvrtom razredu : '); readln(j); j:=j/5*e; d:=f+g+h+j; write('Broj predmeta (ne racunajuci hrvatski jezik, strani jezik i matematiku) koju je ucenik/ca polagao na maturi - '); readln(a); write('Postotak rijesnosti ispita iz hrvatskog jezika te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+b*c; write('Postotak rijesnosti ispita iz stranog jezika te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); write('Postotak rijesnosti ispita iz matematike te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); for i:=1 to a do begin writeln('Postotak rijesnosti dodatnog predmeta te zatim maksimum bodova koje je ucenik/ca mogao ostvariti - '); readln(b); readln(c); d:=d+(b*c); end; d:=round(d); writeln('Vas broj bodova je: ', d:4:2); write('Za nastavak pritisnite ENTER..'); readln; end; procedure unos; begin new(trenutni); write('Redni broj ucenika - ');readln(trenutni^.redni_broj); write('Prezime i ime - ');readln(trenutni^.prezime_ime); write('Naziv fakultet - ');readln(trenutni^.fakultet); write('Bodovi - ');readln(trenutni^.bodovi); trenutni^.sljedeci:=pocetni; pocetni:=trenutni; end; procedure ispis; begin writeln(); writeln('Lista popisanih ucenika:'); writeln(); trenutni:=pocetni; while trenutni<>NIL do begin with trenutni^do begin writeln('IME: ',prezime_ime); writeln('FAKULTET: ',fakultet); writeln('BODOVI: ',bodovi); writeln(); end; trenutni:=trenutni^.sljedeci; end; writeln(); write('Za nastavak pritisnite ENTER..'); readln; end; procedure brisi; var s:string; begin trenutni:= pocetni; prethodni:=pocetni; write('Redni broj ucenika kojeg zelite izbrisati - '); readln(s); while trenutni<>NIL do begin if trenutni^.redni_broj=s then begin prethodni^.sljedeci:=trenutni^.sljedeci; dispose(trenutni); break; end; trenutni:=trenutni^.sljedeci; end; end; procedure izmjeni; var s:string; begin trenutni:=pocetni; write('Redni broj ucenika cije podatke zelite izmijeniti - '); readln(s); while trenutni<> NIL do begin if trenutni^.redni_broj=s then begin write(trenutni^.prezime_ime, ' - '); readln(trenutni^.prezime_ime); write(trenutni^.fakultet, ' - '); readln(trenutni^.fakultet); write(trenutni^.bodovi, ' - '); readln(trenutni^.bodovi); break; end; trenutni:=trenutni^.sljedeci; end; end; **procedure sortiraj; var t1,t2,t:pokazivac; begin t1:=pocetni; while t1 <> NIL do begin t2:=t1^.sljedeci; while t2<>NIL do if t2^.bodovi<t1^.bodovi then begin new(t); t^.redni_broj:=t1^.redni_broj; t^.prezime_ime:=t1^.prezime_ime; t^.fakultet:=t1^.fakultet; t^.bodovi:=t1^.bodovi; t1^.redni_broj:=t2^.redni_broj; t1^.prezime_ime:=t2^.prezime_ime; t1^.fakultet:=t2^.fakultet; t1^.bodovi:=t2^.bodovi; t2^.redni_broj:=t^.redni_broj; t2^.prezime_ime:=t^.prezime_ime; t2^.fakultet:=t^.fakultet; t2^.bodovi:=t^.bodovi; dispose(t); end; t2:=t2^.sljedeci; end; t1:=t1^.sljedeci; write('Za nastavak pritisnite ENTER..'); readln; end;** begin pocetni:=NIL; trenutni:=NIL; writeln('******************************************'); writeln('**********DOBRODOSLI U FAX-O-MAT**********'); writeln('******************************************'); repeat writeln('1 - Racunaj broj bodova'); writeln('2 - Dodaj ucenika'); writeln('3 - Brisi ucenika'); writeln('4 - Ispis liste'); writeln('5 - Izmjeni podatke'); writeln('6 - Sortiraj listu prema broju bodova'); writeln('0 - Kraj'); readln(i); case i of 1:racunaj; 2:unos; 3:brisi; 4:ispis; 5:izmjeni; 6:sortiraj; end; until i=0; end. Either it crashes with a fatal error, or when I press the number 6, nothing happens. The pointer keeps blinking and I can't enter any more numbers.

    Read the article

  • Knockout.js - Filtering, Sorting, and Paging

    - by jtimperley
    Originally posted on: http://geekswithblogs.net/jtimperley/archive/2013/07/28/knockout.js---filtering-sorting-and-paging.aspxKnockout.js is fantastic! Maybe I missed it but it appears to be missing flexible filtering, sorting, and pagination of its grids. This is a summary of my attempt at creating this functionality which has been working out amazingly well for my purposes. Before you continue, this post is not intended to teach you the basics of Knockout. They have already created a fantastic tutorial for this purpose. You'd be wise to review this before you continue. http://learn.knockoutjs.com/ Please view the full source code and functional example on jsFiddle. Below you will find a brief explanation of some of the components. http://jsfiddle.net/JTimperley/pyCTN/13/ First we need to create a model to represent our records. This model is a simple container with defined and guaranteed members. function CustomerModel(data) { if (!data) { data = {}; } var self = this; self.id = data.id; self.name = data.name; self.status = data.status; } Next we need a model to represent the page as a whole with an array of the previously defined records. I have intentionally overlooked the filtering and sorting options for now. Note how the filtering, sorting, and pagination are chained together to accomplish all three goals. This strategy allows each of these pieces to be used selectively based on the page's needs. If you only need sorting, just sort, etc. function CustomerPageModel(data) { if (!data) { data = {}; } var self = this; self.customers = ExtractModels(self, data.customers, CustomerModel); var filters = […]; var sortOptions = […]; self.filter = new FilterModel(filters, self.customers); self.sorter = new SorterModel(sortOptions, self.filter.filteredRecords); self.pager = new PagerModel(self.sorter.orderedRecords); } The code currently supports text box and drop down filters. Text box filters require defining the current 'Value' and the 'RecordValue' function to retrieve the filterable value from the provided record. Drop downs allow defining all possible values, the current option, and the 'RecordValue' as before. Once defining these filters, they are automatically added to the screen and any changes to their values will automatically update the results, causing their sort and pagination to be re-evaluated. var filters = [ { Type: "text", Name: "Name", Value: ko.observable(""), RecordValue: function(record) { return record.name; } }, { Type: "select", Name: "Status", Options: [ GetOption("All", "All", null), GetOption("New", "New", true), GetOption("Recently Modified", "Recently Modified", false) ], CurrentOption: ko.observable(), RecordValue: function(record) { return record.status; } } ]; Sort options are more simplistic and are also automatically added to the screen. Simply provide each option's name and value for the sort drop down as well as function to allow defining how the records are compared. This mechanism can easily be adapted for using table headers as the sort triggers. That strategy hasn't crossed my functionality needs at this point. var sortOptions = [ { Name: "Name", Value: "Name", Sort: function(left, right) { return CompareCaseInsensitive(left.name, right.name); } } ]; Paging options are completely contained by the pager model. Because we will be chaining arrays between our filtering, sorting, and pagination models, the following utility method is used to prevent errors when handing an observable array to another observable array. function GetObservableArray(array) { if (typeof(array) == 'function') { return array; }   return ko.observableArray(array); }

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >