Search Results

Search found 9211 results on 369 pages for 'radix sort'.

Page 9/369 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • Sorting Algorithms

    - by MarkPearl
    General Every time I go back to university I find myself wading through sorting algorithms and their implementation in C++. Up to now I haven’t really appreciated their true value. However as I discovered this last week with Dictionaries in C# – having a knowledge of some basic programming principles can greatly improve the performance of a system and make one think twice about how to tackle a problem. I’m going to cover briefly in this post the following: Selection Sort Insertion Sort Shellsort Quicksort Mergesort Heapsort (not complete) Selection Sort Array based selection sort is a simple approach to sorting an unsorted array. Simply put, it repeats two basic steps to achieve a sorted collection. It starts with a collection of data and repeatedly parses it, each time sorting out one element and reducing the size of the next iteration of parsed data by one. So the first iteration would go something like this… Go through the entire array of data and find the lowest value Place the value at the front of the array The second iteration would go something like this… Go through the array from position two (position one has already been sorted with the smallest value) and find the next lowest value in the array. Place the value at the second position in the array This process would be completed until the entire array had been sorted. A positive about selection sort is that it does not make many item movements. In fact, in a worst case scenario every items is only moved once. Selection sort is however a comparison intensive sort. If you had 10 items in a collection, just to parse the collection you would have 10+9+8+7+6+5+4+3+2=54 comparisons to sort regardless of how sorted the collection was to start with. If you think about it, if you applied selection sort to a collection already sorted, you would still perform relatively the same number of iterations as if it was not sorted at all. Many of the following algorithms try and reduce the number of comparisons if the list is already sorted – leaving one with a best case and worst case scenario for comparisons. Likewise different approaches have different levels of item movement. Depending on what is more expensive, one may give priority to one approach compared to another based on what is more expensive, a comparison or a item move. Insertion Sort Insertion sort tries to reduce the number of key comparisons it performs compared to selection sort by not “doing anything” if things are sorted. Assume you had an collection of numbers in the following order… 10 18 25 30 23 17 45 35 There are 8 elements in the list. If we were to start at the front of the list – 10 18 25 & 30 are already sorted. Element 5 (23) however is smaller than element 4 (30) and so needs to be repositioned. We do this by copying the value at element 5 to a temporary holder, and then begin shifting the elements before it up one. So… Element 5 would be copied to a temporary holder 10 18 25 30 23 17 45 35 – T 23 Element 4 would shift to Element 5 10 18 25 30 30 17 45 35 – T 23 Element 3 would shift to Element 4 10 18 25 25 30 17 45 35 – T 23 Element 2 (18) is smaller than the temporary holder so we put the temporary holder value into Element 3. 10 18 23 25 30 17 45 35 – T 23   We now have a sorted list up to element 6. And so we would repeat the same process by moving element 6 to a temporary value and then shifting everything up by one from element 2 to element 5. As you can see, one major setback for this technique is the shifting values up one – this is because up to now we have been considering the collection to be an array. If however the collection was a linked list, we would not need to shift values up, but merely remove the link from the unsorted value and “reinsert” it in a sorted position. Which would reduce the number of transactions performed on the collection. So.. Insertion sort seems to perform better than selection sort – however an implementation is slightly more complicated. This is typical with most sorting algorithms – generally, greater performance leads to greater complexity. Also, insertion sort performs better if a collection of data is already sorted. If for instance you were handed a sorted collection of size n, then only n number of comparisons would need to be performed to verify that it is sorted. It’s important to note that insertion sort (array based) performs a number item moves – every time an item is “out of place” several items before it get shifted up. Shellsort – Diminishing Increment Sort So up to now we have covered Selection Sort & Insertion Sort. Selection Sort makes many comparisons and insertion sort (with an array) has the potential of making many item movements. Shellsort is an approach that takes the normal insertion sort and tries to reduce the number of item movements. In Shellsort, elements in a collection are viewed as sub-collections of a particular size. Each sub-collection is sorted so that the elements that are far apart move closer to their final position. Suppose we had a collection of 15 elements… 10 20 15 45 36 48 7 60 18 50 2 19 43 30 55 First we may view the collection as 7 sub-collections and sort each sublist, lets say at intervals of 7 10 60 55 – 20 18 – 15 50 – 45 2 – 36 19 – 48 43 – 7 30 10 55 60 – 18 20 – 15 50 – 2 45 – 19 36 – 43 48 – 7 30 (Sorted) We then sort each sublist at a smaller inter – lets say 4 10 55 60 18 – 20 15 50 2 – 45 19 36 43 – 48 7 30 10 18 55 60 – 2 15 20 50 – 19 36 43 45 – 7 30 48 (Sorted) We then sort elements at a distance of 1 (i.e. we apply a normal insertion sort) 10 18 55 60 2 15 20 50 19 36 43 45 7 30 48 2 7 10 15 18 19 20 30 36 43 45 48 50 55 (Sorted) The important thing with shellsort is deciding on the increment sequence of each sub-collection. From what I can tell, there isn’t any definitive method and depending on the order of your elements, different increment sequences may perform better than others. There are however certain increment sequences that you may want to avoid. An even based increment sequence (e.g. 2 4 8 16 32 …) should typically be avoided because it does not allow for even elements to be compared with odd elements until the final sort phase – which in a way would negate many of the benefits of using sub-collections. The performance on the number of comparisons and item movements of Shellsort is hard to determine, however it is considered to be considerably better than the normal insertion sort. Quicksort Quicksort uses a divide and conquer approach to sort a collection of items. The collection is divided into two sub-collections – and the two sub-collections are sorted and combined into one list in such a way that the combined list is sorted. The algorithm is in general pseudo code below… Divide the collection into two sub-collections Quicksort the lower sub-collection Quicksort the upper sub-collection Combine the lower & upper sub-collection together As hinted at above, quicksort uses recursion in its implementation. The real trick with quicksort is to get the lower and upper sub-collections to be of equal size. The size of a sub-collection is determined by what value the pivot is. Once a pivot is determined, one would partition to sub-collections and then repeat the process on each sub collection until you reach the base case. With quicksort, the work is done when dividing the sub-collections into lower & upper collections. The actual combining of the lower & upper sub-collections at the end is relatively simple since every element in the lower sub-collection is smaller than the smallest element in the upper sub-collection. Mergesort With quicksort, the average-case complexity was O(nlog2n) however the worst case complexity was still O(N*N). Mergesort improves on quicksort by always having a complexity of O(nlog2n) regardless of the best or worst case. So how does it do this? Mergesort makes use of the divide and conquer approach to partition a collection into two sub-collections. It then sorts each sub-collection and combines the sorted sub-collections into one sorted collection. The general algorithm for mergesort is as follows… Divide the collection into two sub-collections Mergesort the first sub-collection Mergesort the second sub-collection Merge the first sub-collection and the second sub-collection As you can see.. it still pretty much looks like quicksort – so lets see where it differs… Firstly, mergesort differs from quicksort in how it partitions the sub-collections. Instead of having a pivot – merge sort partitions each sub-collection based on size so that the first and second sub-collection of relatively the same size. This dividing keeps getting repeated until the sub-collections are the size of a single element. If a sub-collection is one element in size – it is now sorted! So the trick is how do we put all these sub-collections together so that they maintain their sorted order. Sorted sub-collections are merged into a sorted collection by comparing the elements of the sub-collection and then adjusting the sorted collection. Lets have a look at a few examples… Assume 2 sub-collections with 1 element each 10 & 20 Compare the first element of the first sub-collection with the first element of the second sub-collection. Take the smallest of the two and place it as the first element in the sorted collection. In this scenario 10 is smaller than 20 so 10 is taken from sub-collection 1 leaving that sub-collection empty, which means by default the next smallest element is in sub-collection 2 (20). So the sorted collection would be 10 20 Lets assume 2 sub-collections with 2 elements each 10 20 & 15 19 So… again we would Compare 10 with 15 – 10 is the winner so we add it to our sorted collection (10) leaving us with 20 & 15 19 Compare 20 with 15 – 15 is the winner so we add it to our sorted collection (10 15) leaving us with 20 & 19 Compare 20 with 19 – 19 is the winner so we add it to our sorted collection (10 15 19) leaving us with 20 & _ 20 is by default the winner so our sorted collection is 10 15 19 20. Make sense? Heapsort (still needs to be completed) So by now I am tired of sorting algorithms and trying to remember why they were so important. I think every year I go through this stuff I wonder to myself why are we made to learn about selection sort and insertion sort if they are so bad – why didn’t we just skip to Mergesort & Quicksort. I guess the only explanation I have for this is that sometimes you learn things so that you can implement them in future – and other times you learn things so that you know it isn’t the best way of implementing things and that you don’t need to implement it in future. Anyhow… luckily this is going to be the last one of my sorts for today. The first step in heapsort is to convert a collection of data into a heap. After the data is converted into a heap, sorting begins… So what is the definition of a heap? If we have to convert a collection of data into a heap, how do we know when it is a heap and when it is not? The definition of a heap is as follows: A heap is a list in which each element contains a key, such that the key in the element at position k in the list is at least as large as the key in the element at position 2k +1 (if it exists) and 2k + 2 (if it exists). Does that make sense? At first glance I’m thinking what the heck??? But then after re-reading my notes I see that we are doing something different – up to now we have really looked at data as an array or sequential collection of data that we need to sort – a heap represents data in a slightly different way – although the data is stored in a sequential collection, for a sequential collection of data to be in a valid heap – it is “semi sorted”. Let me try and explain a bit further with an example… Example 1 of Potential Heap Data Assume we had a collection of numbers as follows 1[1] 2[2] 3[3] 4[4] 5[5] 6[6] For this to be a valid heap element with value of 1 at position [1] needs to be greater or equal to the element at position [3] (2k +1) and position [4] (2k +2). So in the above example, the collection of numbers is not in a valid heap. Example 2 of Potential Heap Data Lets look at another collection of numbers as follows 6[1] 5[2] 4[3] 3[4] 2[5] 1[6] Is this a valid heap? Well… element with the value 6 at position 1 must be greater or equal to the element at position [3] and position [4]. Is 6 > 4 and 6 > 3? Yes it is. Lets look at element 5 as position 2. It must be greater than the values at [4] & [5]. Is 5 > 3 and 5 > 2? Yes it is. If you continued to examine this second collection of data you would find that it is in a valid heap based on the definition of a heap.

    Read the article

  • perl sorting an array of hashes

    - by srk
    use strict; my @arr; $arr[0][0]{5} = 16; $arr[0][1]{6} = 11; $arr[0][2]{7} = 25; $arr[0][3]{8} = 31; $arr[0][4]{9} = 16; $arr[0][5]{10} = 17; sort the array based on hash values so this should change to $arr[0][0]{6} = 11; $arr[0][1]{9} = 16; $arr[0][2]{5} = 16; $arr[0][3]{10} = 17; $arr[0][4]{7} = 25; $arr[0][5]{8} = 31; first sort on values in the hash.. when the values are same reverse sort based on keys... Please tell me how to do this.. Thank you

    Read the article

  • HTML5 : Microsoft sort deux modules Websocket et IndexedDB pour IE9 et tester ces standards "encore instables"

    HTML5 : Microsoft propose des modules pour Websocket et IndexedDB Installables sur la bêta d'Internet Explorer 9 Microsoft vient de lancer un site dédié aux standards HTML5 ouverts, une manière de permettre aux développeurs d'expérimenter des standards qui ne seront pas intégrés à Internet Explorer avant leur finalisation par le W3C. Une approche qui se veut plus prudente et pragmatique que celles de ces concurrents, qui n'hésitent pas, eux, à implémenter - au moins partiellement - des standards en gestation dans les versions grand public de leurs navigateurs. Appelé HTML5 Labs, ce nouveau site propose, pour ses débuts, deux modules. Le premier est le...

    Read the article

  • Oracle sort Oracle Application Express 4.2, son outil de développement rapide intégré à Oracle Database

    Oracle Application Express, l'outil de développement rapide d'Oracle est désormais disponible en version 4.2. Cet outil, intégré à Oracle Database sans coût supplémentaire, permet de développer des applications Web exploitant les données d'une base Oracle. Cette mise à jour est très centrée vers le mobile et apporte un certain nombre de nouveautés pour le développement d'applications mobiles avec APEX. Notons en particulier :Le rendu des applications qui s'adaptent pour proposer une interface adaptée au terminal mobile utilisé L'utilisation de jQuery Mobile qui permet la compatibilité sur la majorité des terminaux sans modification La possibilité de créer des graphiques en HTML5 pour les terminaux ne disposant pas de Flash L'utilisat...

    Read the article

  • ZeroTurnaround sort la version 3.1 de son outil de productivité Java JRebel et améliore son support

    Outre des corrections d'anomalies, JRebel supporte désormais les changements dans le mapping Object Relationnel pour les implémentations de JPA que sont Hibernate et OpenJPA. Toplink/EclipseLink est également pris en charge mais c'est encore expérimental (à activer si vous souhaitez tester). Au rayon de l'accès aux données, il y a également désormais une prise en charge des modifications de sql maps pour iBatis.

    Read the article

  • Merge sort. ArrayIndexOutOfBoundsException [migrated]

    - by user94892
    When I execute the program I am getting an error as stated below the program. Please help me figure out the problem.. import java.util.*; class Mergesort { public static void main(String args[]) { Scanner in= new Scanner(System.in); System.out.println("Enter the number of elements"); int n= in.nextInt(); int a[]= new int[n]; System.out.println("Enter the contents"); for(int i=0; i<n; i++) { a[i]=in.nextInt(); } a = mergesort(a,n); for(int i=0; i<n; i++) { System.out.println(a[i]); } } public static int[] mergesort(int[] x, int z) { if(z==1) { return x; } int b[]=new int[z/2]; int c[]=new int[z-z/2]; int i,j,k; for(int p=0;p<z/2; p++) { b[p]= x[p]; c[p]= x[p+z/2]; } c[z-z/2-1]= x[z-1]; b= mergesort(b,z/2); c= mergesort(c,z-z/2); for(i=0,j=0,k=0; k<z; k++) { if(b[i]<=c[j]) { x[k]=b[i]; i++; } else if( b[i]>c[j]) { x[k]=c[j]; j++; } else if(i== z/2) { x[k]= c[j]; j++; } else if(j == z-z/2) { x[k]= b[i]; i++; } } return x; } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Mergesort.mergesort(Mergesort.java:41) at Mergesort.mergesort(Mergesort.java:36) at Mergesort.main(Mergesort.java:16)

    Read the article

  • What sort of leaderboard for my game?

    - by Martin
    I recently published a word game for Windows Phone and I am really happy to have some players. The game is entirely offline and at the end of a game, the player's score is published to a server. I'm collecting the scores to build a leaderboard. Right now, I don't believe that the leaderboard I offer to my users is appropriate. I essentially accumulate the score of all the games of a user for a given day and that becomes their score. So if Player 1 plays 3 games and gets 100, 150 and 200 points, its score for the day is 450 points. I would like to get your ideas and opinion. How do I keep my game challenging and engaging with a good leaderboard? Should I continue accumulating the score for a day? Should I just keep the best score? Thanks!

    Read the article

  • Force Your Mac to Sort Folders on Top of Files (Windows Style)

    - by Eric Z Goodnight
    Even die-hard Mac converts have their issues with Mac OS, and one of those problems is that OS X lists folders mixed in with all other files. Here’s how to fix that in under five minutes with a clever hack. You know you’ve had that issue. You’ve dug through your files looking for that one elusive folder, and because it’s jumbled in with all the other stuff, it’s more or less impossible to find. Have no fear, with no downloads or silly plug-in software, you can finally make Mac OS behave like Windows and Linux and list those folders in the proper order.  How To Encrypt Your Cloud-Based Drive with BoxcryptorHTG Explains: Photography with Film-Based CamerasHow to Clean Your Dirty Smartphone (Without Breaking Something)

    Read the article

  • Adobe sort Project Parfait, un outil en ligne pour extraire le CSS de votre PSD

    Adobe Project Parfait : extraire le CSS de votre PSDAdobe signe un bel outil qui promet de rendre de bons services aux webmaster en permettant d'extraire le code CSS d'un fichier PSD dans le navigateur. Dans le navigateur? C'est à dire que la version actuelle (beta) est gratuite et ne nécessite pas de posséder Photoshop pour l'utiliser.On peut imaginer que le webmaster a reçu la maquette d'une page en PSD qu'il lui suffit d'uploader sur Project Parfait pour en extraire le CSS.L'interface intuitive...

    Read the article

  • Windows 7 Enterprise : Microsoft sort une version d'évaluation gratuite de l'édition "réservée aux professionnels de l'informatique"

    Microsoft propose une version d'évaluation gratuite de Windows 7 Enterprise Que pensez-vous de cette édition spécialement dédiée aux professionnels de l'informatique Le 8 avril 2014, Windows XP sera de l'histoire ancienne pour Microsoft. Plus aucune mise à jour et plus aucun support ne seront proposés pour le système d'exploitation n°1 dans le monde. Vista a suivi mais a déboussolé tant d'utilisateurs que pour beaucoup de professionnels IT, le vrai successeur de Windows XP est en fait Windows 7. Et plus exactement Windows 7 Enterprise. Au moment où Microsoft vient de lancer une offre spéciale de 90 jours d'essai gratuit pour cette édition spéciale (justement en rapport avec...

    Read the article

  • How to sort time column by value instead of alphabetically

    - by Turch
    I'm creating a pivot table by connecting to an SSAS tabular model (Data - From Other Sources - From Analysis Services) . The model has a "time" column that I want to sort by. The default (database) sorting is earliest to latest: When I click the triangle next to 'Row Labels' and select "Sort A to Z", I get alphabetically sorted times: How can I get the times to sort by time? Changing the number format from "General" to "Time" does nothing. The times aren't stored as text either - the data type of the column in the SSAS model is Auto (Date)

    Read the article

  • Sort rectangles in a grid based on a comparison of the center point of each

    - by Mrwolfy
    If I have a grid of rectangles and I move one of the rectangles, say above and to the left of another rectangle, how would I resort the rectangles? Note the rectangles are in an array, so each rectangle has an index and a matching tag. All I really need to do is set the proper index based on the rectangles new center point position within the rectangle, as compared with the center point position of the other rectangles in the grid. Here is what I am doing now in pseudo code (works somewhat, but not accurate): -(void)sortViews:myView { int newIndex; // myView is the view that was moved. [viewsArray removeObject:myView]; [viewsArray enumerate:obj*view]{ if (myView.center.x > view.center.x) { if (myView.center.y > view.center.y) { newIndex = view.tag -1; *stop = YES; } else { newIndex = view.tag +1; *stop = YES; } } else if (myView.center.x < view.center.x) { if (myView.center.y > view.center.y) { newIndex = view.tag -1; *stop = YES; } else { newIndex = view.tag +1; *stop = YES; } } }]; if (newIndex < 0) { newIndex = 0; } else if (newIndex > 5) { newIndex = 5; } [viewsArray insertObject:myView atIndex:newIndex]; [self arrangeGrid]; }

    Read the article

  • Lucene neo4j sort with boolean fields

    - by Daniele
    I have indexed some documents (nodes of neo4j) with a boolean property which not always is present. Eg. Node1 label : "label A" Node2: label : "label A" (note, same label of node1) special : true The goal is to get Node2 higher than node 1 for query "label A". Here the code: Index<Node> fulltextLucene = graphDb.index().forNodes( "my-index" ); Sort sort = new Sort(new SortField[] {SortField.FIELD_SCORE, new SortField("special", SortField.????, true) }); IndexHits<Node> results = fulltextLucene.query( "label", new QueryContext( "label A").sort(sort)); How can I accomplish that? Thanks

    Read the article

  • Maintaining sort order of database table rows

    - by Lox
    Say I have at database table containing information about a news article in each row. The table has an integer "sort" column to dictate the order in which the articles are to be presented on a web site. How do I best implement and maintain this sort order. The problem I want to avoid is having the the articles numbered 1,2,3,4,..,100 and when article number 50 suddenly becomes interesting it gets its sort number set to 1 and then all articles between them must have their sort number increased by one. Sure, setting initial sort numbers to 100,200,300,400 etc. leaves some space for moving around but at some point it will break. Is there a correct way to do this, maybe a completely different approach? Added-1: All article titles are shown in a list linking to the contents, so yes all sorted items are show at once. Added-2: An item is not necessarily moved to the top of the list; any item can be placed anywhere in the ordered list.

    Read the article

  • Prolog: using the sort/2 predicate

    - by Øyvind Hauge
    So I'm trying to get rid of the wrapper clause by using the sort library predicate directly inside split. What split does is just generating a list of numbers from a list that looks like this: [1:2,3:2,4:6] ---split-- [1,2,3,2,4,6]. But the generated list contains duplicates, and I don't want that, so I'm using the wrapper to combine split and sort, which then generates the desired result: [1,2,3,4,6]. I'd really like to get rid of the wrapper and just use sort within split, however I keep getting "ERROR: sort/2: Arguments are not sufficiently instantiated." Any ideas? Thanks :) split([],[]). split([H1:H2|T],[H1,H2|NT]) :- split(T,NT). wrapper(L,Processed) :- split(L,L2), sort(L2,Processed).

    Read the article

  • Virtual methods as Comp function to sort

    - by wilsongoncalo.mp
    Hello everyone! I'm new to C++ and i'm trying to use std::sort function to sort a vector of Solutions. The code is something like this (solution list is a *vector): void SolutionSet::sort(Comparator &comparator) { std::sort(solutionsList_->begin(), solutionsList_->end(), &comparator::compare); } The comparator param is a Comparator´s child class instance , and the compare method is virtual at Comparator class and implemented by all Comparator's child classes. And i want to use that function as a comparator function at std:sort(). Is this possible? If it is, can someone tell me how? Because with the previous code, it doesn't work. If i've not made myself clear, please just ask! Thank you guys!

    Read the article

  • Shell Sort problem

    - by user191603
    Show the result of running Shell Sort on the input 9,8,7,6,5,4,3,2,1 using increments { 1,3,7 }. I have done this part. the result is: 9 8 7 6 5 4 3 2 1 (original) 2 1 7 6 5 4 3 9 8 ( 7-sort ) 2 1 4 3 5 7 6 9 8 ( 3-sort ) 1 2 3 4 5 6 7 8 9 ( 1-sort ) Then the question requires me to determine the running time of Shell Sort using Shell's increments of N/2, N/4, ..., 1 for sorted input. I am not quite sure how to answer the second question as I don't understand the requirement of this question. So, would anyone give some hints to let me finish this question? Thank you for your help first!

    Read the article

  • sort list(of string()) using a variable index into string() as key - vb.net

    - by tullynyguy
    I have a List(of String()). I have written a custom comparer (implements IComparer(of string)) to do an alphanumeric sort. Is there a way to sort the List using a given index to determine which position in the String() to sort by? In other words one time I might sort by Index = 0 and another time by Index = 3. The length of all String() in the list is the same. For reference this question is similar to Sort List<String[]> except I am using VB.net and that question is hardwired to Index=0.

    Read the article

  • efficient sort with custom comparison, but no callback function

    - by rob
    I have a need for an efficient sort that doesn't have a callback, but is as customizable as using qsort(). What I want is for it to work like an iterator, where it continuously calls into the sort API in a loop until it is done, doing the comparison in the loop rather than off in a callback function. This way the custom comparison is local to the calling function (and therefore has access to local variables, is potentially more efficient, etc). I have implemented this for an inefficient selection sort, but need it to be efficient, so prefer a quick sort derivative. Has anyone done anything like this? I tried to do it for quick sort, but trying to turn the algorithm inside out hurt my brain too much. Below is how it might look in use. // the array of data we are sorting MyData array[5000], *firstP, *secondP; // (assume data is filled in) Sorter sorter; // initialize sorter int result = sortInit (&sorter, array, 5000, (void **)&firstP, (void **)&secondP, sizeof(MyData)); // loop until complete while (sortIteration (&sorter, result) == 0) { // here's where we do the custom comparison...here we // just sort by member "value" but we could do anything result = firstP->value - secondP->value; }

    Read the article

  • Any 3rd party tools that integrate IIS management with some sort of application inventory/change man

    - by NoCarrier
    I've got an environment with several IIS 6 web servers hosting hundreds of apps (dozens of sites, hundreds of virtual directories) all with a myriad of different configurations belonging to dozens of different developers (all deploying apps willy nilly). Is there some sort of managed software solution that will centralize management of all my IIS6 environments provide some inventory functionality allow for reporting or querying of said application inventory enforce and automate some sort of deployment process?

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >