Search Results

Search found 9186 results on 368 pages for 'sort'.

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

  • Efficient way to sort large set of numbers

    - by 7Aces
    I have to sort a set of 100000 integers as a part of a programming Q. The time limit is pretty restrictive, so I have to use the most time-efficient approach possible. My current code - #include<cstdio> #include<algorithm> using namespace std; int main() { int n,d[100000],i; for(i=0;i<n;++i) { scanf("%d",&d[i]); } sort(d,d+n); .... } Would this approach be more efiicient? int main() { int n,d[100000],i; for(i=0;i<n;++i) { scanf("%d",&d[i]); sort(d,d+i+1); } .... } What is the most efficient way to sort a large dataset? Note - Not homework...

    Read the article

  • Ruby: Why is Array.sort slow for large objects?

    - by David Waller
    A colleague needed to sort an array of ActiveRecord objects in a Rails app. He tried the obvious Array.sort! but it seemed surprisingly slow, taking 32s for an array of 3700 objects. So just in case it was these big fat objects slowing things down, he reimplemented the sort by sorting an array of small objects, then reordering the original array of ActiveRecord objects to match - as shown in the code below. Tada! The sort now takes 700ms. That really surprised me. Does Ruby's sort method end up copying objects about the place rather than just references? He's using Ruby 1.8.6/7. def self.sort_events(events) event_sorters = Array.new(events.length) {|i| EventSorter.new(i, events[i])} event_sorters.sort! event_sorters.collect {|es| events[es.index]} end private # Class used by sort_events class EventSorter attr_reader :sqn attr_reader :time attr_reader :index def initialize(index, event) @index = index @sqn = event.sqn @time = event.time end def <=>(b) @time != b.time ? @time <=> b.time : @sqn <=> b.sqn end end

    Read the article

  • Can I sort files A-Z and at the same time Z-A?

    - by The_Buff
    I am trying to sort and rename a large number of files that are labeled #####_## The LEFT side of the underscore are numbers (e.g., 32956715, 32956810, etc.) that do not repeat. The RIGHT side of the underscore are also numbers (e.g., 1, 2, 3, etc.) and they do repeat. (The left side is the number of a scan and the right side is the page of that particular scan.) I would like to be able to sort the left side of the underscore Z-A and the right side A-Z. Example: 3_1 3_2 3_3 2_1 2_2 2_3 1_1 1_2 1_3 I am using ReNamer by den4b (easily the best free renamer out there). It supports regular expressions so I believe there should be an easy way to do this, but I don't know how. (I've been trying to learn regular expressions but I don't use them enough to retain anything.) I'm open for any suggestions that achieve the same result. I've spent enough time trying to figure it out that I could have probably just sorted them myself already but this is a reccuring problem so hopefully someone has a solution that will save me lots of time in the long run. Thank You!

    Read the article

  • ArrayList.Sort should be a stable sort with an IComparer but is not?

    - by Kaleb Pederson
    A stable sort is a sort that maintains the relative ordering of elements with the same value. The docs on ArrayList.Sort say that when an IComparer is provided the sort is stable: If comparer is set to null, this method performs a comparison sort (also called an unstable sort); that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. To perform a stable sort, you must implement a custom IComparer interface. Unless I'm missing something, the following testcase shows that ArrayList.Sort is not using a stable sort: internal class DisplayOrdered { public int ID { get; set; } public int DisplayOrder { get; set; } public override string ToString() { return string.Format("ID: {0}, DisplayOrder: {1}", ID, DisplayOrder); } } internal class DisplayOrderedComparer : IComparer { public int Compare(object x, object y) { return ((DisplayOrdered)x).DisplayOrder - ((DisplayOrdered)y).DisplayOrder; } } [TestFixture] public class ArrayListStableSortTest { [Test] public void TestWeblinkCallArrayListIsSortedUsingStableSort() { var call1 = new DisplayOrdered {ID = 1, DisplayOrder = 0}; var call2 = new DisplayOrdered {ID = 2, DisplayOrder = 0}; var call3 = new DisplayOrdered {ID = 3, DisplayOrder = 2}; var list = new ArrayList {call1, call2, call3}; list.Sort(new DisplayOrderedComparer()); // expected order (by ID): 1, 2, 3 (because the DisplayOrder // is equal for ID's 1 and 2, their ordering should be // maintained for a stable sort.) Assert.AreEqual(call1, list[0]); // Actual: ID=2 ** FAILS Assert.AreEqual(call2, list[1]); // Actual: ID=1 Assert.AreEqual(call3, list[2]); // Actual: ID=3 } } Am I missing something? If not, would this be a documentation bug or a library bug? Apparently using an OrderBy in Linq gives a stable sort.

    Read the article

  • Sort Data in Windows Phone using Collection View Source

    - by psheriff
    When you write a Windows Phone application you will most likely consume data from a web service somewhere. If that service returns data to you in a sort order that you do not want, you have an easy alternative to sort the data without writing any C# or VB code. You use the built-in CollectionViewSource object in XAML to perform the sorting for you. This assumes that you can get the data into a collection that implements the IEnumerable or IList interfaces.For this example, I will be using a simple Product class with two properties, and a list of Product objects using the Generic List class. Try this out by creating a Product class as shown in the following code:public class Product {  public Product(int id, string name)   {    ProductId = id;    ProductName = name;  }  public int ProductId { get; set; }  public string ProductName { get; set; }}Create a collection class that initializes a property called DataCollection with some sample data as shown in the code below:public class Products : List<Product>{  public Products()  {    InitCollection();  }  public List<Product> DataCollection { get; set; }  List<Product> InitCollection()  {    DataCollection = new List<Product>();    DataCollection.Add(new Product(3,        "PDSA .NET Productivity Framework"));    DataCollection.Add(new Product(1,        "Haystack Code Generator for .NET"));    DataCollection.Add(new Product(2,        "Fundamentals of .NET eBook"));    return DataCollection;  }}Notice that the data added to the collection is not in any particular order. Create a Windows Phone page and add two XML namespaces to the Page.xmlns:scm="clr-namespace:System.ComponentModel;assembly=System.Windows"xmlns:local="clr-namespace:WPSortData"The 'local' namespace is an alias to the name of the project that you created (in this case WPSortData). The 'scm' namespace references the System.Windows.dll and is needed for the SortDescription class that you will use for sorting the data. Create a phone:PhoneApplicationPage.Resources section in your Windows Phone page that looks like the following:<phone:PhoneApplicationPage.Resources>  <local:Products x:Key="products" />  <CollectionViewSource x:Key="prodCollection"      Source="{Binding Source={StaticResource products},                       Path=DataCollection}">    <CollectionViewSource.SortDescriptions>      <scm:SortDescription PropertyName="ProductName"                           Direction="Ascending" />    </CollectionViewSource.SortDescriptions>  </CollectionViewSource></phone:PhoneApplicationPage.Resources>The first line of code in the resources section creates an instance of your Products class. The constructor of the Products class calls the InitCollection method which creates three Product objects and adds them to the DataCollection property of the Products class. Once the Products object is instantiated you now add a CollectionViewSource object in XAML using the Products object as the source of the data to this collection. A CollectionViewSource has a SortDescriptions collection that allows you to specify a set of SortDescription objects. Each object can set a PropertyName and a Direction property. As you see in the above code you set the PropertyName equal to the ProductName property of the Product object and tell it to sort in an Ascending direction.All you have to do now is to create a ListBox control and set its ItemsSource property to the CollectionViewSource object. The ListBox displays the data in sorted order by ProductName and you did not have to write any LINQ queries or write other code to sort the data!<ListBox    ItemsSource="{Binding Source={StaticResource prodCollection}}"   DisplayMemberPath="ProductName" />SummaryIn this blog post you learned that you can sort any data without having to change the source code of where the data comes from. Simply feed the data into a CollectionViewSource in XAML and set some sort descriptions in XAML and the rest is done for you! This comes in very handy when you are consuming data from a source where the data is given to you and you do not have control over the sorting.NOTE: You can download this article and many samples like the one shown in this blog entry at my website. http://www.pdsa.com/downloads. Select “Tips and Tricks”, then “Sort Data in Windows Phone using Collection View Source” from the drop down list.Good Luck with your Coding,Paul Sheriff** SPECIAL OFFER FOR MY BLOG READERS **We frequently offer a FREE gift for readers of my blog. Visit http://www.pdsa.com/Event/Blog for your FREE gift!

    Read the article

  • Sorting Arrays by More the One Value, and Prioritizing the Sort based on Column data.

    - by Mark Tomlin
    I'm looking for a way to sort an array (we call this a row), with an array of values (that I'll call columns). Each row has columns that must be sorted based on the priority of: timetime, lapcount & timestamp. Each column cotains this information: split1, split2, split3, laptime, lapcount, timestamp. laptime if in hundredths of a second. (1:23.45 or 1 Minute, 23 Seconds & 45 Hundredths is 8345.) Lapcount is a simple unsigned tiny int, or unsigned char. timestamp is unix epoch. The lowest laptime should be at the get a better standing in this sort. Should two peoples laptimes equal, then timestamp will be used to give the better standing in this sort. Should two peoples timestamp equal, then the person with less of a lapcount get's the better standing in this sort. By better standing, I mean closer to the top of the array, closer to the index of zero where it a numerical array. I think the array sorting functions built into php can do this with a callback, I was wondering what the best approch was for a weighted sort like this would be.

    Read the article

  • Sorting Arrays by More the One Value, and Prioritizing the Sort based on Column data.

    - by Mark Tomlin
    I'm looking for a way to sort an array, based on the information in each row, based on the information in certain cells, that I'll call columns. Each row has columns that must be sorted based on the priority of: timetime, lapcount & timestamp. Each column cotains this information: split1, split2, split3, laptime, lapcount, timestamp. laptime if in hundredths of a second. (1:23.45 or 1 Minute, 23 Seconds & 45 Hundredths is 8345.) Lapcount is a simple unsigned tiny int, or unsigned char. timestamp is unix epoch. The lowest laptime should be at the get a better standing in this sort. Should two peoples laptimes equal, then timestamp will be used to give the better standing in this sort. Should two peoples timestamp equal, then the person with less of a lapcount get's the better standing in this sort. By better standing, I mean closer to the top of the array, closer to the index of zero where it a numerical array. I think the array sorting functions built into php can do this with a callback, I was wondering what the best approch was for a weighted sort like this would be.

    Read the article

  • How to sort an array or ArrayList<Point> ASC first by x and then by y?

    - by newba
    Hi everyone, I just want to use Collections.sort or Arrays.sort to sort a list of points (class Point) by x first and then by y. I have a class Ponto that implements Comparable like this: public int compareTo(Ponto obj) { Ponto tmp = obj; if (this.x < tmp.x) { return -1; } else if (this.x > tmp.x) { return 1; } return 0; } but now I want to sort by y too after x. How can I do that by modifying the above code? Or is that a better and "clean" way to do this? I also use to pass this code to C++, in which I've created a structure called Point with a equivalent comparable method.

    Read the article

  • In XSLT, how can you sort using an indirect key?

    - by edholder
    I am having trouble getting xsl:sort to understand the scope of the attributes I am referencing. Here is an XML sample document to illustrate: <Root> <DrinkSelections> <Drink id=1000 name="Coffee"/> <Drink id=1001 name="Water"/> <Drink id=1002 name="Tea"/> <Drink id=1003 name="Almost But Not Quite Entirely Unlike Tea"/> </DrinkSelections> <CustomerOrder> <Drinks> <Drink oid="1001"/> <Drink oid="1002"/> <Drink oid="1003"/> </Drinks> </CustomerOrder </Root> I want to produce a list of drinks (sorted by name) contained in the CustomerOrder. Here is the XSLT code I am fiddling with: <xsl:for-each select="/Root/CustomerOrder/Drinks/Drink"> <xsl:sort select="/Root/DrinkSelections/Drink[@id = @oid]/@name"/> <xsl:variable name=var_oid select="@oid"/> <xsl:value-of select="/Root/DrinkSelections/Drink[@id = $var_oid]/@name"/> </xsl:for-each> Apparently, the xsl:sort command is trying to apply the "oid" attribute to the Drink elements in DrinkSelections, rather than local Drink element. I can get around this using a variable, as in the xsl:value-of statement. But since xsl:sort must be the first statement after the xsl:for-each statement, I can't insert the xsl:variable statement before xsl:sort. Is there a way to explicitly state that the attribute value should be taken from the "local" element?

    Read the article

  • How can I sort du -h output by size

    - by Tom Feiner
    I need to get a list of human readable du output. However, du does not have a "sort by size" option, and piping to "sort" doesn't work with the human readable flag. For example, running: du | sort -n -r Outputs a sorted disk usage by size (descending): du |sort -n -r 65108 . 61508 ./dir3 2056 ./dir4 1032 ./dir1 508 ./dir2 However, running it with the human readable flag, does not sort properly: du -h | sort -n -r 508K ./dir2 64M . 61M ./dir3 2.1M ./dir4 1.1M ./dir1 Does anyone know of a way to sort du -h by size?

    Read the article

  • Why does C qicksort function implementation works much slower (tape comparations, tape swapping) than bobble sort function?

    - by Artur Mustafin
    I'm going to implement a toy tape "mainframe" for a students, showing the quickness of "quicksort" class functions (recursive or not, does not really matters, due to the slow hardware, and well known stack reversal techniques) comparatively to the "bubblesort" function class, so, while I'm clear about the hardware implementation ans controllers, i guessed that quicksort function is much faster that other ones in terms of sequence, order and comparation distance (it is much faster to rewind the tape from the middle than from the very end, because of different speed of rewind). Unfortunately, this is not the true, this simple "bubble" code shows great improvements comparatively to the "quicksort" functions in terms of comparison distances, direction and number of comparisons and writes. So I have 3 questions: Does I have mistaken in my implememtation of quicksort function? Does I have mistaken in my implememtation of bubblesoft function? If not, why the "bubblesort" function is works much faster in (comparison and write operations) than "quicksort" function? I already have a "quicksort" function: void quicksort(float *a, long l, long r, const compare_function& compare) { long i=l, j=r, temp, m=(l+r)/2; if (l == r) return; if (l == r-1) { if (compare(a, l, r)) { swap(a, l, r); } return; } if (l < r-1) { while (1) { i = l; j = r; while (i < m && !compare(a, i, m)) i++; while (m < j && !compare(a, m, j)) j--; if (i >= j) { break; } swap(a, i, j); } if (l < m) quicksort(a, l, m, compare); if (m < r) quicksort(a, m, r, compare); return; } } and the kind of my own implememtation of the "bubblesort" function: void bubblesort(float *a, long l, long r, const compare_function& compare) { long i, j, k; if (l == r) { return; } if (l == r-1) { if (compare(a, l, r)) { swap(a, l, r); } return; } if (l < r-1) { while(l < r) { i = l; j = l; while (i < r) { i++; if (!compare(a, j, i)) { continue; } j = i; } if (l < j) { swap(a, l, j); } l++; i = r; k = r; while(l < i) { i--; if (!compare(a, i, k)) { continue; } k = i; } if (k < r) { swap(a, k, r); } r--; } return; } } I have used this sort functions in a test sample code, like this: #include <stdio.h> #include <stdlib.h> #include <math.h> #include <conio.h> long swap_count; long compare_count; typedef long (*compare_function)(float *, long, long ); typedef void (*sort_function)(float *, long , long , const compare_function& ); void init(float *, long ); void print(float *, long ); void sort(float *, long, const sort_function& ); void swap(float *a, long l, long r); long less(float *a, long l, long r); long greater(float *a, long l, long r); void bubblesort(float *, long , long , const compare_function& ); void quicksort(float *, long , long , const compare_function& ); void main() { int n; printf("n="); scanf("%d",&n); printf("\r\n"); long i; float *a = (float *)malloc(n*n*sizeof(float)); sort(a, n, &bubblesort); print(a, n); sort(a, n, &quicksort); print(a, n); free(a); } long less(float *a, long l, long r) { compare_count++; return *(a+l) < *(a+r) ? 1 : 0; } long greater(float *a, long l, long r) { compare_count++; return *(a+l) > *(a+r) ? 1 : 0; } void swap(float *a, long l, long r) { swap_count++; float temp; temp = *(a+l); *(a+l) = *(a+r); *(a+r) = temp; } float tg(float x) { return tan(x); } float ctg(float x) { return 1.0/tan(x); } void init(float *m,long n) { long i,j; for (i = 0; i < n; i++) { for (j=0; j< n; j++) { m[i + j*n] = tg(0.2*(i+1)) + ctg(0.3*(j+1)); } } } void print(float *m, long n) { long i, j; for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { printf(" %5.1f", m[i + j*n]); } printf("\r\n"); } printf("\r\n"); } void sort(float *a, long n, const sort_function& sort) { long i, sort_compare = 0, sort_swap = 0; init(a,n); for(i = 0; i < n*n; i+=n) { if (fmod (i / n, 2) == 0) { compare_count = 0; swap_count = 0; sort(a, i, i+n-1, &less); if (swap_count == 0) { compare_count = 0; sort(a, i, i+n-1, &greater); } sort_compare += compare_count; sort_swap += swap_count; } } printf("compare=%ld\r\n", sort_compare); printf("swap=%ld\r\n", sort_swap); printf("\r\n"); }

    Read the article

  • How would I sort files to directories based on filenames?

    - by gnomed
    I have a huge number of files to sort all named in some terrible convention. Here are some examples: (4)_mr__mcloughlin____.txt 12__sir_john_farr____.txt (b)mr__chope____.txt dame_elaine_kellett-bowman____.txt dr__blackburn______.txt These names are supposed to be a different person (speaker) each. Someone in another IT department produced these from a ton of XML files using some script but the naming is unfathomably stupid as you can see. I need to sort literally tens of thousands of these files with multiple files of text for each person; each with something stupid making the filename different, be it more underscores or some random number. They need to be sorted by speaker. This would be easier with a script to do most of the work then I could just go back and merge folders that should be under the same name or whatever. There are a number of ways I was thinking about doing this. parse the names from each file and sort them into folders for each unique name. get a list of all the unique names from the filenames, then look through this simplified list of unique names for similar ones and ask me whether they are the same, and once it has determined this it will sort them all accordingly. I plan on using Perl, but I can try a new language if it's worth it. I'm not sure how to go about reading in each filename in a directory one at a time into a string for parsing into an actual name. I'm not completely sure how to parse with regex in perl either, but that might be googleable. For the sorting, I was just gonna use the shell command: `cp filename.txt /example/destination/filename.txt` but just cause that's all I know so it's easiest. I dont even have a pseudocode idea of what im going to do either so if someone knows the best sequence of actions, im all ears. I guess I am looking for a lot of help, I am open to any suggestions. Many many many thanks to anyone who can help. B.

    Read the article

  • sort utility on cyrillic text

    - by Anton
    I have to sort some lines of cyrillic characters and I want to use the sort utility (on MAC OS X 10.6). The problem is that result is incorrect. I take the text into clipboard, then run pbpaste | sort This is plaintext data, and I also tried passing a file to the sort command. My source data is ??????? ????? ???? ???? ?????? ??????? ???????? ?????? ? ????? ??????????????? ?????????? ???? ?????? And after sorting I get ???? ???? ???? ????? ?????? ?????? ?????? ? ????? ??????????????? ??????? ??????? ???????? ?????????? Theese lines aren’t even grouped by first letter. I tried option -d, but then I get an error sort: string comparison failed: Illegal byte sequence sort: Set LC_ALL='C' to work around the problem. sort: The strings compared were \320\321\321\321' and\320\320\320\321\321\320’. Exporting the variable as recommended doesn’t solve the problem. What can I do to use the sort utility for such a task? Any additional info is necessary?

    Read the article

  • How do I sort a multidimensional hash array by a key maybe three levels in, in PHP?

    - by Chris Denman
    I am moving from Perl to PHP and am struggling to get my head around PHP sorting. Here's what I have in Perl: $log{12345}{0}{20100102}{name}='blah'; $log{54312}{1}{20100101}{name}='blah'; $log{14323}{3}{20100103}{name}='blah'; foreach $entry (sort {$log{$cook}{$a}{time} cmp $log{$cook}{$b}{time}} keys %{$log{$cook}}){ ... } Basically, I would have the same array structure in PHP but want to sort like I do above.

    Read the article

  • What's the best way to store sort order in SQL?

    - by Duracell
    The guys at the top want sort order to be customizable in our app. So I have a table that effectively defines the data type. What is the best way to store our sort order. If I just created a new column called 'Order' or something, every time I updated the order of one row I imagine I would have to update the order of every row to ensure posterity. Is there a better way to do it?

    Read the article

  • jQuery: Sort div's according to content of different sub divs

    - by rayne
    I'm trying to create a somewhat complex sorting feature which neither uses divs nor lists. Unfortunately two hours of googling didn't help me. Here is the basic setup of my HTML: <div id="all_elements"> <!-- one element --> <div class="element"> <div class="wrapper"> <a href="/" title="links"> <img src="/img/image.jpg" border="0" alt="image" class="image" /></a> <div class="details"> <h3><a href="/" title="title">Name (Sort Argument 1)</a></h3> <div class="title"><a href="/" title="title">Title (Sort Argument 2)</a></div> <div class="year">2010 (Sort Argumentt 3)</div> <div class="country">Great Britain (Sort Argument 4)</div> </div><!-- details --> </div><!-- wrapper --> </div><!-- element --> </div> <!--all_elements--> The setup is a bit complex, but basically .element is the element that needs to be sorted alphabetically according to either the contents of h3, div.title, div.year or div.country. So the user will be able to view the contents of the site either sorted by name, by year, by country or by title. I have this jQuery snippet from a website, but all my attempts on trying to tell it to use the contents of e.g. h3 to sort have failed. Right now it sorts pretty much randomly. jQuery.fn.sort = function() { return this.pushStack([].sort.apply(this, arguments), []); }; function sortAscending(a, b) { return a.innerHTML > b.innerHTML ? 1 : -1; }; function sortDescending(a, b) { return a.innerHTML < b.innerHTML ? 1 : -1; }; $(document).ready(function() { $("#sort").toggle( function() { $('#all_elements .element').sort(sortDescending).appendTo('#all_elements'); $(this).text("Sort Asc"); }, function() { $('#all_elements .element').sort(sortAscending).appendTo('#all_elements'); $(this).text("Sort Desc"); }); }); How can I customize the function to sort the contents of my h3 or divs?

    Read the article

  • Unix sort 10x slower with keys specified

    - by KenFar
    My data: It's a 71 MB file with 1.5 million rows. It has 6 fields, four of which are strings of avg. 15 characters, two are integers. Three of the fields are sometimes empty. All six fields combine to form a unique key - and that's what I need to sort on. Sort statement: sort -t ',' -k1,1 -k2,2 -k3,3 -k4,4 -k5,5 -k6,6 -o a_out.csv a_in.csv The problem: If I sort without keys, it takes 30 seconds. If I sort with keys, it takes 660 seconds. I need to sort with keys to keep this generic and useful for other files that have non-key fields as well. The 30 second timing is fine, but the 660 is a killer. I could theoretically move the temp directory to SSD, and/or split the file into 4 parts, sort them separately (in parallel) then merge the results, etc. But I'm hoping for something simpler since these results are so bad as-is. Any suggestions?

    Read the article

  • How do I sort a hash table in javascript?

    - by Colen
    I have a javascript hash table, like so: var things = [ ]; things["hello"] = {"name" : "zzz I fell asleep", "number" : 7}; things["one"] = {"name" : "something", "number" : 18}; things["two"] = {"name" : "another thing", "number" : -2}; I want to sort these into order by name, so if I iterate through the hash table it will go in order another thing something zzz I fell asleep I tried doing this: function compareThings(thing1, thing2) { var name1 = thing1["name"].toLowerCase(); var name2 = thing2["name"].toLowerCase(); if (name1 < name2) { return -1; } if (name1 > name2) { return 1; } return 0; } things.sort(compareThings); But it doesn't seem to work. Edit: it occurs to me that perhaps a sorted hash table is an oxymoron. If so, what's the best way to get access to a sorted list of the things here?

    Read the article

  • how to implement a really efficient bitvector sorting in python

    - by xiao
    Hello guys! Actually this is an interesting topic from programming pearls, sorting 10 digits telephone numbers in a limited memory with an efficient algorithm. You can find the whole story here What I am interested in is just how fast the implementation could be in python. I have done a naive implementation with the module bitvector. The code is as following: from BitVector import BitVector import timeit import random import time import sys def sort(input_li): return sorted(input_li) def vec_sort(input_li): bv = BitVector( size = len(input_li) ) for i in input_li: bv[i] = 1 res_li = [] for i in range(len(bv)): if bv[i]: res_li.append(i) return res_li if __name__ == "__main__": test_data = range(int(sys.argv[1])) print 'test_data size is:', sys.argv[1] random.shuffle(test_data) start = time.time() sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "sort function takes " + str(elapsed) start = time.time() vec_sort(test_data) elapsed = (time.time() - start) print "vec_sort function takes " + str(elapsed) I have tested from array size 100 to 10,000,000 in my macbook(2GHz Intel Core 2 Duo 2GB SDRAM), the result is as following: test_data size is: 1000 sort function takes 0.000274896621704 vec_sort function takes 0.00383687019348 test_data size is: 10000 sort function takes 0.00380706787109 vec_sort function takes 0.0371489524841 test_data size is: 100000 sort function takes 0.0520560741425 vec_sort function takes 0.374383926392 test_data size is: 1000000 sort function takes 0.867373943329 vec_sort function takes 3.80475401878 test_data size is: 10000000 sort function takes 12.9204008579 vec_sort function takes 38.8053860664 What disappoints me is that even when the test_data size is 100,000,000, the sort function is still faster than vec_sort. Is there any way to accelerate the vec_sort function?

    Read the article

  • How to sort an NSMutableArray of objects by a member of its class, that is an int or float

    - by J. Dave
    I have a class (from NSObject) that contains: NSString name int position float speed I then create an array (NSMutableArray) of objects from this class. I would like to then sort the array by the 'speed' value, which is a float. I initially has the float value as an NSNumber and the int as NSInteger, and I was successfully sorting with: [myMutableArray sortUsingFunction:compareSelector context:@selector(position)]; where myMutableArray is my array of objects. here is the function: static int compareSelector(id p1, id p2, void *context) { SEL methodSelector = (SEL)context; id value1 = [p1 performSelector:methodSelector]; id value2 = [p2 performSelector:methodSelector]; return [value1 compare:value2]; } Now that I am using int instead of NSInteger, the above code does not work. Is there a more low-level command that I should be using to execute the sort? Thank!

    Read the article

  • Algorithm to Sort member into groups

    - by kasmanit
    I'll have to develop an application which the final purpose is to sort all the member into groups. Each group will have the same size. And I had to put the members into the groups several times during the execution of the program. To put the member into the groups, a lot of critria are to be look at, because we do not want that two people are put again together two time in the same execution of the program, of course if it's the only way to find a correct solution, it' fine, and there is a lot of other criteria, like some people can be willing to be always with another member. So to resume, we have n members to put in groups of size 8. After the first "round" we have to do again the algorithm to sort them differently. And a lot of critria may go in the calculation of the priority of each member Do you have any idea?

    Read the article

  • Sort an array via x86 Assembly (embedded in C++)?? Possible??

    - by Mark V.
    I am playing around with x86 assembly for the first time and I can't figure out how to sort an array (via insertion sort).. I understand the algorithm, but assembly is confusing me as I primarily use Java & C++. Heres all I have so far int ascending_sort( char arrayOfLetters[], int arraySize ) { char temp; __asm{ push eax push ebx push ecx push edx push esi push edi //// ??? pop edi pop esi pop edx pop ecx pop ebx pop eax } } Basically nothing :( Any ideas?? Thanks in advance.

    Read the article

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