Jump to content

Sorting algorithms

Nineshadow

WIP

This post will go over a few of the most popular sorting algorithms out there. Even though most programming languages have built-in sorting, it's still a good idea to know how some of those techniques work. I hope a few of you will learn something from it , even though there already are quite a few sources in which you can also learn them.

 

First of all, I will explain the methods , but the actual coding will be done in C++. If you aren't familiar to this programming language, then here is something you should know :

In C++, you can't parse an array to a function per-se, as in parsing a collection of values.

 

Let's try to make a function that writes an array to the console :

You might have the surprise that it won't work(if you were expecting it to work).That's because an array in C++ is a pointer, the pointer to the first element in the array. So, instead of parsing an actual collection of numbers, we will only be parsing the pointer to the first element of the array.

Of course, you can still do this :

That's because in C++ , an array is a pointer. So, this :

is equivalent to :

It's just that accessing the values is a little different. This :

becomes :

Since *arr points to the beginning of the array.

 

If you don't know what pointers are you should definitely learn them.

 

A really quick introduction to pointers :

 

From its name, it's pretty obvious that a pointer points to something, in our case a pointer points to another value stored in our memory using its address.

 

In C++, the declaration of a pointer is as follows :

For example :

"int" is our type, and "p" is our variable name.

 

To get the address of a variable, we use the "&" prefix before a variable. This is called the address-of operator.

This will output the address of the variable n.

We can use that to store a pointer with the value of the address of another variable :

We can also get the value at the exact space in our memory to which a pointer points to, using the "*" prefix. This is called the dereference operator.

Note that a pointer stores the memory address, not the value at that memory address.

 

Let's start with probably the most basic sorting algorithm :

 

Bubblesort

Bubblesort is the easiest sorting algorithm out there. It works like this :

 

Our function has 2 inputs : the pointer of the array, and its length.

Considering we have a vector of size n, we'll go through it between indexes of 0 and n-1.

If the value at the current index(i) is bigger than the one at the next one(i+1), then the array is obviously not sorted, so we swap them. This is also the reason why our previous 'for' only went to (array length -1) , because otherwise we would have gone out of its bounds.

Here's a quick swap function :

If we look at what effect our code has, we'll see that it brings the biggest number to the last position in the array. But we've still got the rest of them unsorted. This means we'll have to repeat our code from before. Since we will go through the array at least once, no matter its contents, we could use a do-while loop.

But when do we stop? How can we check if the array is already ordered to stop unnecessary steps? Pretty simple. We'll make a boolean value in which we'll store whether our array is sorted or not. In the do-while loop we'll set it to true, assuming the array is already sorted. Then, in our for loop, if we do find numbers in an incorrect order, we'll make it false.

 

Our bubble-sort algorithm becomes :

In pseudocode :

As far as optimization goes, we could also ignore the last numbers we already know are in their sorted position.

Bubblesort is one of the worst sorting algorithms out there, but the simplest to understand.It's worst-case complexity is O(n2), with usually O(n2) swaps as well.

 

Insertion sort

 

Asympotically equivalent to bubblesort,but much faster in practice.

The idea behind insertion sort is pretty simple as well :

 

You have a sorted array. You're given a number that you need to insert in the right place so the array is still sorted. Thus, you compare this number against the other ones untill you find the right place. Then again, and again, until you're out of numbers.

 

So, let's make an insertion algorithm. The input will consist of the pointer to the array, a right index which will allow us to work with subarrays, and the actual value we want to insert.

Let's say we have the ordered array [ 0 , 1 , 2 , 5 , 6 , 7] and we wanted to insert 4 in there.

Pretty simple. We go from the right-most element, until we reach one which is smaller then our original number - 4. In our case, that would happen with the number at index 2, ironically being the number 2 as well. But wait, we have a small problem. We can't just write it there. We need to shift all numbers from the index in which our original one will reside to the right.

We do that quite easily :

Now, let's come back to our original problem. We need to exit our loop when we reach a number smaller than ours, and we need to put it into a certain index of the array.

Our insert function becomes :

Now, we need to build a sorting algorithm which uses it. The subarray consisting of the first element is already sorted, so we'll start from the second. We insert it into our subarray[0...0] (from 0 to 0). Then we go for the third number, inserting it into our subarray[0...1]. And so on.

Our insert function :

Count-sort (I think?)

I haven't really seen this algorithm too often, but it's relatively simple. More efficient than previous sorting algorithms execution-time-wise, but memory management is terrible.

The idea behind it is, as I've said, really simple, we count the number of appearances of each value in our original array.

We go through our array and we find its maximum.

Then, we create a secondary array with the size maximum+1.The purpose of this array is to count how many numbers of each value there are in the array.

For example, our original array is [1, 5, 3 ,1 ,0 ,2].

Our counting array will hold :

  • at index 0 : 1 (since there is only one 0)
  • at index 1 : 2 (since there are two of 1)
  • at index 2 : 1
  • at index 3 : 1
  • at index 4: 0 (since there is no 4 in our array)
  • at index 5 : 1

Quite simple, yes? The only real problem is working with large numbers. Imagine if the maximum number in our array was something like 29. Bad luck.

 

Anyway, let's make our counting array :

let's first initialize it to 0.

Then, we go through the original array. We'll increment the value in the count array at the index equal to the value in our original array.

Now, we just need to make our ordered array :

Our function becomes :

This algorithm uses a lot of memory and is only useful for small integers, or, with right optimization, integers which are pretty close in value.

 

We can optimize this algorithm a little. Let's say we have an array [54,51,53,52]. It would be pointless to make an array with the size 55 to count each apparition of the numbers between 0 and 54 in our array we want to sort. Knowing the minimum value in an array, we can reduce both the memory usage (sometimes greatly!), and the execution time(a little).

When we look for the maximum value in the array, we'll also look for the minimum.

We'll make initialize a min first :

Then, to find the minimum :

Then we'll just have to change the initialization of our "count" array :

I think it's pretty obvious why we chose max - min + 1 as the size of the array.

 

Our optimized algorithm is :
 

Merge sort

Ah, we've stepped into the world of divide et impera algorithms (divide and conquer). Our full problem is to sort an entire array. Our subproblem is to sort a subarray, starting at index p and ending at index r of an original array : array[p..r]. So, to sort an entire array, we would have to sort the subarray [0..n-1].

 

Then we do as follows:

  • we find the middle index between p and r, let's call it q. This is our divide step.
  • we recursively sort the resulting two subarrays : array[p,q] and array[q+1,r].This is our conquer step.
  • we then merge the two sorted subarrays into a single sorted one.

We also need a base case, which is a subarray with a single element, which happens when p>= r. Thus, we'll only apply our algorithm if p < r.

 

Let's have an example.

Our array is [-2 , 5 , 0 ,4 , 3 , 2].

p = 0

r = 5

We calculate q = 2.

Our subarrays are [-2, 5 , 0] and [4, 3 ,2].

These will then be sorted recursively, by doing the same thing , again and again until we reach our base case.

So, our arrays are now sorted, but we still need to merge them into a singular one.We will also need a merging function.

 

Merge-Sort.png

We know what the merge function would do, we do not know yet how we are implementing it, but we can still go ahead and make our merge sort function:

Pretty straight-forward.

We'll also make a function that only takes the array and its length as an input, for easier use :

Now let's get to our merge function!

For input, it will need the array, our begining, middle, and end.(p,q,r).

 

The subarrays have already been sorted recursively. Now we just need to put them together and end up with an array that is still sorted.

For example, we have the subarrays : [1 , 2 , 4] and [0, 3 , 5]

We want to end up with [0, 1 , 2 , 3 , 4 , 5].

It's pretty simple.

First we want to backup our subarrays, so we don't overwrite them.

Let's call them lowerHalf( between p and q) and higherHalf(between q and r).

Their sizes are as follows :

  • lowHalf -> q-p+1
  • highHalf -> r-q

Then, we'll compare the first elements from each array, then we write the smallest one of the two.

We'll also need to use a counter to store where we need to write in our original array.

But then what? Let's say our original arrays were [1 , 2 , 4] and [0, 3 ,5].

Our so-far sorted array is [0], a number which came from highHalf. Then, we'll want to compare still the first number from lowHalf, which has not yet been used, and the second one from highHalf.

We'll use the variable i for lowHalf and the variable j for highHalf, while keeping k for the original array. k must obviously be equal to p.

Oh, almost forgot, we first have to initialize our lowHalf and highHalf arrays.

Then, we'll set i and j to 0, and reset k to p.

Now let's go through the comparing what number to use, from lowHalf or highHalf :

But wait, we could reach the end of lowHalf before the end of highHalf. We obviously need to keep inserting elements until both arrays are finished.

Our merge algorithm becomes :

Merge sort is quite fast, with a time complexity of O(n log n).

 

Quicksort

Ah yes, here it is!Like merge sort, it's a recursive divide et impera algorithm. In merge sort, the divide step does hardly anything, and all the real work happens in the combine step. Quicksort is the opposite: all the real work happens in the divide step. In fact, the combine step in quicksort does absolutely nothing.

Its worst-case running time is as bad as selection sort's and insertion sort's: O(n2). But its average-case running time is as good as merge sort's: O(n log n). So why think about quicksort when merge sort is at least as good? That's because the constant factor hidden in the big-Θ notation for quicksort is quite good. In practice, quicksort outperforms merge sort, and it significantly outperforms selection sort and insertion sort.

 

Again, we will be sorting a subarray[p..r].

We divide by chosing a pivot, usually it's the right-most element.Then we arrange our subarray so all elements smaller than our pivot are to its left, and all elements bigger than it are to its right. This is called partitioning.

 

We then recursively sort the arrays [p..q-1] and [q+1..r], where q is the index at which the pivot ends up after the partitioning.

 

Let's take an example.

To sort the subarray [4, 2, 3], we choose 3 as the pivot. After partitioning, we have [2, 3, 4]. The subarray [2], to the left of the pivot, is a base case when we recurse, as is the subarray [4], to the right of the pivot.

To sort the subarray [12, 7, 14, 9, 10, 11], we choose 11 as the pivot, resulting in [7, 9, 10] to the left of the pivot and [14, 12] to the right. After these subarrays are sorted, we have [7, 9, 10], followed by 11, followed by [12, 14].

 

We'll need a partitioning function. We will implement it later, let's first make our quicksort function, which is quite simple :

As you can see, the partition function not only does the partitioning, but also returns the value at which the pivot ends up.

 

Now comes the real deal, the partition function.

We divide our array into 4 groups :

  1. the elements in the array[p..q-1] are elements known to be less or equal than the pivot.
  2. elements in the array[q..j] are elements known to be bigger than the pivot. j will be a new variable.
  3. elements in the array [j..r-1] are elements which we haven't compared to the pivot yet.
  4. at array[r] we have our pivot

Initially, both q and j are equal to p, since we do not have any elements known to be bigger nor smaller than the pivot, since we haven't compared anything yet.

If you think about it another way,our j variable will be used for scanning through the entire array. At each step, it increments. If the value at array[j] is bigger than the pivot, then nothing else happens. If it's smaller or equal, then it also increments q.

partition_greater.png- first case, with a number bigger than the pivot

 

 

 

partition_less_equal.png-second case, a number smaller than the pivot

 

Once we get through the entire array, we swap array[r] with array[q], also while returning q.

 

All of these being said in a more compact manner :

  • Compare array[j] with array[r], for j = p, p+1,...r-1 maintaining that:
  •   array[p..q-1] are values known to be <= to array[r]
  •   array[q..j-1] are values known to be > array[r]
  •   array[j..r-1] haven't been compared with array[r]
  • If array[j] > array[r], just increment j.
  • If array[j] <= array[r], swap array[j] with array[q], increment q, and increment j.
  • Once all elements in array[p..r-1] have been compared with array[r],swap array[r] with array[q], and return q.

Our partition function becomes :

HEAP SORT :

Work in progress.

 

Placeholder code :

void cout_array(int array[]){for(int i = 0; i < sizeof(array)/sizeof(array[0]); i++)cout << array[i];}int v[...];cout_array(v);
void cout_array(int *array, array_length){for(int i = 0; i < array_length; i++)std::cout << *(array+i);}int v[<size>];/*or int *v = new int[<size>];*/cout_array(v, <size>);
void function(int array[]) { ... }
int arr[];
int *arr;
arr[i] = <value>
*(arr+i) = <value>
<type> *<variable_name>;
int *p;
int n = 100;cout << &n;
int n = 100;int *p = &n;
int n = 100;int *p = &n;cout << "Value " << *p << "in memory at : " << p;
void bubblesort(int *arr, int array_length){
for(int i =0; i < array_length-1; i++)if(*(arr+i) > *(arr+i+1)) swap(arr, i, i+1);
void swap(int *arr, index1, index2){int aux = *(arr + index1);*(arr + index1) = *(arr + index2);*(arr + index2) = aux;}
do{for(int i =0; i < array_length-1; i++)if(*(arr+i) > *(arr+i+1)) swap(arr, i, i+1);}while(<condition>)
void bubblesort(int* ar, int ar_length){    bool is_sorted;    do    {        is_sorted = true;        for(int i = 0; i < ar_length-1; i++)            if(*(ar+i) > *(ar+i+1))            {                is_sorted = false;                swap(arr, i , i+1);            }    }    while(!is_sorted);}
func bubblesort( var a as array )    do         sorted = 1        for i from 0 to n-2            if a[i] > a[i+1]               swap(a[i], a[i+1])               sorted = 0    while sorted == 1end func
void bubblesort(int* ar, int ar_length){    bool is_sorted;    int k = 1;    do    {        is_sorted = true;        for(int i = 0; i < ar_length-k; i++)            if(*(ar+i) > *(ar+i+1))            {                is_sorted = false;                swap(arr, i , i+1);            }        k++;    }    while(!is_sorted);}
 int i;    for(i = right_index; i >= 0; i--  )        *(ar + i+1) = *(ar + i);
void insert(int *ar, int right_index, int value){    int i;    for(i = right_index; (i >= 0) && ( value < *(ar + i) ); i--  )        *(ar + i+1) = *(ar + i);    *(ar+i+1) = value;}
void insertsort(int *ar, int ar_length){    for(int i = 1; i < ar_length; i++) insert(ar, i-1, *(ar+i));}
 int max = -999999999;    for(int i = 0; i < ar_length;i++)        if(*(ar+i) > max) max = *(ar+i);
int v[max+1];
for(int i = 0; i < max+1;i++)        v[i]=0;
for(int i = 0; i < ar_length;i++)        v[*(ar+i)]++;
int k = 0;    for(int i = 0; i < max+1;i++){        while(v[i]--)        *(ar+k++) = i;    }
void countSort(int *ar, int ar_length){    int max = -999999999;    for(int i = 0; i < ar_length;i++)        if(*(ar+i) > max) max = *(ar+i);    int v[max+1];    for(int i = 0; i < max+1;i++)        v[i]=0;    for(int i = 0; i < ar_length;i++)        v[*(ar+i)]++;    int k = 0;    for(int i = 0; i < max+1;i++){        while(v[i]--)        *(ar+k++) = i;    }}
int min = 999999999;
  for(int i = 0; i < ar_length;i++)    {        //find max        if(*(ar+i) > max) max = *(ar+i);        //find min        if(*(ar+i) < min) min = *(ar+i);    }
int v[max+1-min];
void countSort(int *ar, int ar_length){    int max = -999999999;    int min = 999999999;    for(int i = 0; i < ar_length;i++)    {        if(*(ar+i) > max) max = *(ar+i);        if(*(ar+i) < min) min = *(ar+i);    }    int v[max+1-min];    for(int i = 0; i < max+1;i++)        v[i]=0;    for(int i = 0; i < ar_length;i++)        v[*(ar+i)]++;    int k = 0;    for(int i = 0; i < max+1;i++){        while(v[i]--)        *(ar+k++) = i;    }}
void mergeSort(int *ar, int p, int r){    if(p < r)    {        int q = (p + r)/2;        mergeSort(ar,p,q);        mergeSort(ar,q+1,r);        merge(ar, p, q ,r);    }}
void mergesSort(int *ar, int ar_length){    mergeSort(ar, 0, ar_length-1);}
int lowHalf[q-p+1];int highHalf[r-q];
int i, j, k = p;    for(i=0; k<=q; i++,k++) *(lowHalf+i) = *(ar+k);    for(j =0; k<=r; j++,k++) *(highHalf+j) = *(ar+k);
 k = p;    i = 0;    j = 0;
while((i < q-p+1) && (j < r-q))    {        if(*(lowHalf+i) <= *(highHalf+j))        {            *(ar+k) = *(lowHalf+i++);        }        else        {            *(ar+k) = *(highHalf+j++);        }        k++;    }
 while(i < q-p+1)    {        *(ar+k++) = *(lowHalf+i++);    }    while(j < r-q)    {        *(ar+k++) = *(highHalf+j++);    }
void merge(int *ar, int p , int q, int r){    int lowHalf[q-p+1];    int highHalf[r-q];    int i, j, k = p;    for(i=0; k<=q; i++,k++) *(lowHalf+i) = *(ar+k);    for(j =0; k<=r; j++,k++) *(highHalf+j) = *(ar+k);    k = p;    i = 0;    j = 0;    while((i < q-p+1) && (j < r-q))    {        if(*(lowHalf+i) <= *(highHalf+j))        {            *(ar+k) = *(lowHalf+i++);        }        else        {            *(ar+k) = *(highHalf+j++);        }        k++;    }    while(i < q-p+1)    {        *(ar+k++) = *(lowHalf+i++);    }    while(j < r-q)    {        *(ar+k++) = *(highHalf+j++);    }}
void quicksort(int *ar, int p , int r){    if(p<r){        int q = partition(ar, p , r);        quicksort(ar,p,q-1);        quicksort(ar,q+1,r);    }}
int partition(int* ar, int p , int r){    int q = p;    for(int j = p; j < r; j++)    if(*(ar+j) <= *(ar+r)){        swap(ar,j,q);        q++;    }    swap(ar,r,q);    return q;}
void heapSort(int numbers[], int array_size) {  int i, temp;   for (i = (array_size / 2); i >= 0; i--) {    siftDown(numbers, i, array_size - 1);  }   for (i = array_size-1; i >= 1; i--) {    // Swap    temp = numbers[0];    numbers[0] = numbers[i];    numbers[i] = temp;     siftDown(numbers, 0, i-1);  }} void siftDown(int numbers[], int root, int bottom) {  int maxChild = root * 2 + 1;   // Find the biggest child  if(maxChild < bottom) {    int otherChild = maxChild + 1;    // Reversed for stability    maxChild = (numbers[otherChild] > numbers[maxChild])?otherChild:maxChild;  } else {    // Don't overflow    if(maxChild > bottom) return;  }   // If we have the correct ordering, we are done.  if(numbers[root] >= numbers[maxChild]) return;   // Swap  int temp = numbers[root];  numbers[root] = numbers[maxChild];  numbers[maxChild] = temp;   // Tail queue recursion. Will be compiled as a loop with correct compiler switches.  siftDown(numbers, maxChild, bottom);}

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

ayyyy just learned this a few months ago

took me a while to memorize all of them until i started using bogosort in every assignments for my class :P

teacher was kind of mad buy bogosort is the most fun sorting algorism

 

 

there's an interesting youtube video that kind of explains them btw 

Link to comment
Share on other sites

Link to post
Share on other sites

I could have done with this a few months ago when I was doing a report on various sorting and searching algorithms xD

Link to comment
Share on other sites

Link to post
Share on other sites

ayyyy just learned this a few months ago

took me a while to memorize all of them until i started using bogosort in every assignments for my class :P

teacher was kind of mad buy bogosort is the most fun sorting algorism

 

 

there's an interesting youtube video that kind of explains them btw https://www.youtube.com/watch?v=kPRA0W1kECg

Oh, you disappoint me.

You aren't using quantum bogosort!

 

The quantum Bogo Sort algorithm goes like this

1. Take the pack of cards

2. Throw it up in the air

3. Collect the cards

4. Check if they're in Order

    If yes, You have your required answer

    else, the universe is destroyed along with its notion of time

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

I could have done with this a few months ago when I was doing a report on various sorting and searching algorithms xD

That's why I've done it actually.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Oh, you disappoint me.

You aren't using quantum bogosort!

 

The quantum Bogo Sort algorithm goes like this

1. Take the pack of cards

2. Throw it up in the air

3. Collect the cards

4. Check if they're in Order

    If yes, You have your required answer

    else, the universe is destroyed along with its notion of time

our teacher made us write a program that would sort numbers 1-50

everyone else's program took about 2 minutes but mine took 3 hours

Link to comment
Share on other sites

Link to post
Share on other sites

The only sorting algorithms that are actually useful are heap sort, insertion sort, bucket sort and quick sort, AFAIK.

 

For general purpose I think Quick sort which turns into Heap sort after a recursion limit is hit is usually used.

 

Heap sort is good for anything that needs a small memory footprint, since it's in place. Quick sort is O(log(n)) memory because it requires a stack. Merge sort is O(n)  memory I think.

 

Insertion sort is extremely fast on very small sets and sets that are mostly sorted already.

 

Bucket sort is useful on anything where you have a lot of data in a small fixed range, which is very niche. I think your count sort is bucket sort.

Link to comment
Share on other sites

Link to post
Share on other sites

The only sorting algorithms that are actually useful are heap sort, insertion sort, bucket sort and quick sort, AFAIK.

Depends on what you mean by useful, Java, Python and some other languages default sorting algorithm is Timsort.

1474412270.2748842

Link to comment
Share on other sites

Link to post
Share on other sites

Depends on what you mean by useful, Java, Python and some other languages default sorting algorithm is Timsort.

I never knew about timsort. I guess that should be added to the list.

Link to comment
Share on other sites

Link to post
Share on other sites

Radix sort is also a really interesting one, since it runs in O(n) instead of the usual O(n log(n)). It can also be modified to sort floats.
This website explains it very well: http://codercorner.com/RadixSortRevisited.htm


Also some of my favourite joke sorting algo's

Sleep sort:

 

  Create a thread per element, let them sleep x ms, where x is the value of the element. Push them into to an array.

 

Bogus sort:

   while(list is not sorted)     shuffle list

Stack sort: https://gkoberger.github.io/stacksort/
 

Link to comment
Share on other sites

Link to post
Share on other sites

why has no one thought of merge bogo sort yet? You divide the array into arrays of 2 like you would with merge sort, but then instead of doing an ordered merge, you shuffle them together until they are sorted. There was an algorithm along those lines that I read would on average take until the heat death of the universe for a reasonable sized array.

 

 

Sleep sort:

 

  Create a thread per element, let them sleep x ms, where x is the value of the element. Push them into to an array.

 

It should be noted that that will only work reliably on a hard realtime system.

Link to comment
Share on other sites

Link to post
Share on other sites

  • 2 weeks later...

You deserve more like for the effort in trying to explain the topic.

Well done!

Just remembered I have to update this.

Wow.

 

Thanks.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

http://www.sorting-algorithms.com/

 

a website with silly willy animations for your education ( you have to click on the double arrows on the upper left of the table ).

 

But usually the only algorithms worth something are the quicksort and probably the radix sort too in contexts with big data .

Link to comment
Share on other sites

Link to post
Share on other sites

UPDATE 1 :

Optimized the count sort algorithm.

Added a little more stuff in the intro.

Fixed some typos.

Added a heapsort non-recursive implementation, no explaination of the algorithm though.

_________________________________________________

 

Now, I'll have to ask you guys, what other sorting algorithms do you want to see?

TimSort?

Radix?

Others?

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

I decided to try implementing my terrible sorting algorithm idea. I couldn't get it to sort more than 7 numbers with a 200 MB stack size. lol

 

edit: I think I figured out how to fix the stack overflow problem with tail recursion. I'll update with results if it works. might take a few hours to sort all 8 numbers though.

 

update: it looks like it works, but sorting an 8 int array seems like it'll take a few days

void shuffle(int *unshuffled, int len){		int shuffled[len];	char mask[len];		for (int i = 0; i < len; i++) mask[i] = 0;		for (int j, i = 0; i < len; i++)	{		do		{			j = rand() % len;		}		while(mask[j] != 0);		mask[j] = 1;		shuffled[j] = unshuffled[i];	}		memcpy(unshuffled, shuffled, len * sizeof(int));}/*if length > 2, call crap_sort on both halves of the arrayshuffle the unsorted array aroundif not sorted, call crap_sort*/void crap_sort(int *unsorted, int len){	crap_sort_start:	if (len > 2)	{		int left_len = len/2;		crap_sort(unsorted, left_len);		crap_sort(unsorted + left_len, len - left_len);	}		shuffle(unsorted, len);		for (int i = 1; i < len; i++)	{		if (unsorted[i] < unsorted[i - 1])		{			goto crap_sort_start;		}	}}
Link to comment
Share on other sites

Link to post
Share on other sites

Nice post, I like that you're trying to explain a concept and various solutions to it while still just helping people out not giving 100% answers but still being informative. The programming section on the forum needs more posts like this and less "finish my CS homework" posts. Keep up the awesome work, and hopefully you'll make some more posts like this for different concepts in the future.

"Her tsundere ratio is 8:2. So don't think you could see her dere side so easily."


Planing to make you debut here on the forums? Read Me First!


unofficial LTT Anime Club Heaven Society

Link to comment
Share on other sites

Link to post
Share on other sites

Nice post, I like that you're trying to explain a concept and various solutions to it while still just helping people out not giving 100% answers but still being informative. The programming section on the forum needs more posts like this and less "finish my CS homework" posts. Keep up the awesome work, and hopefully you'll make some more posts like this for different concepts in the future.

I've done one on optimizing programs using bitwise operators.

You don't encounter situations like that too often, but hey, they're fun <3.

http://linustechtips.com/main/topic/412487-optimizing-programs-using-bitwise-operations/

 

Thanks.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×