0

Simple logic for quick sorting on cpp?

i tried and reffered many programs they where really twisty and complex

13th Nov 2016, 1:15 PM
Sandeep T L
Sandeep T L - avatar
4 Respuestas
+ 3
The easiest one is the Bubble Sort algorithm, which would look something like this: int arry[5]; arry[0] = 3; arry[1] = 2; arry[2] = 5; arry[3] = 1; arry[4] = 4; for (int range = 0; range < len(arry) - 1; range ++) { for (int iter = 0; iter < len(arry) - 1; iter++) { if (arry[iter] < arry[iter + 1] { // Swap (Note, ^ means XOR) arry[iter] = arry[iter] ^ arry[iter + 1] arry[iter + 1] = arry[iter] ^ arry[iter + 1] arry[iter] = arry[iter] ^ arry[iter + 1] } } Output: 32514 35241 53421 54321
13th Nov 2016, 1:36 PM
Keto Z
Keto Z - avatar
+ 3
Are you referring to quicksort or just "quick sorting"? :D Either way, sorting is a huge topic and whole books have been written on it. There are of course simple algorithms you can even come up with yourself, for example selection sort: 1. find the smallest element in your pile 2. put it into the sorted list 3. go to step 1 The problem with selection sort is that it's not really that fast (if you have n elements you need around n² comparisons). Quicksort is one of the fastest sorting algorithms, and it goes roughly like this: 1. take the center element of your list (called the "pivot") 2. put all the elements that are smaller than the pivot into one list (call it "left") 3. put all the elements that are larger (or equal) than the pivot into another list (call it "right") 4. recursively call quicksort(left) and quicksort(right) 5. concatenate the lists like `left + [pivot] + right`, and that's your result It performs a lot better than the simple algorithms (around n log n comparisons for n elements)
13th Nov 2016, 1:41 PM
Schindlabua
Schindlabua - avatar
+ 2
You can choose any element as the pivot, yeah. There's even "randomized quicksort" where you pick pivots at random. There are tons of quicksort implementations online, just use google. Here's one I found: http://stackoverflow.com/questions/11975214
13th Nov 2016, 2:28 PM
Schindlabua
Schindlabua - avatar
0
thanks but some text says that pivot number is selected as the first element and from right to left checking we select element less than pivot and and interchange with pivot and from left to right we select element greater than pivot and interchange.and this process continues until pivot is in right place.left elements should be less than pivot and right element should bw greater.and for final steps we divide pivots right amd left elements for further sorting.i dont know how to implement it in program.help me with a simple program please
13th Nov 2016, 2:19 PM
Sandeep T L
Sandeep T L - avatar