Skip to content

Commit

Permalink
Added quicksort C implementation (#16)
Browse files Browse the repository at this point in the history
* feat: added quicksort c implementation

* docs: added entry to README

* chore: optimized code

* refactor: added comments

* refactor: refactored code
  • Loading branch information
aviaryan authored and singhpratyush committed Mar 9, 2017
1 parent d838d18 commit 02257d1
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Community (college) maintained list of algorithm implementations and codes.
| Algorithm | C | CPP | Java | Python |
|:--------------|:----------------:|:----------------:|:----------------:|:-----------------:|
| [Linear Search](https://en.wikipedia.org/wiki/Linear_search) | | | | [\[X\]](linear_search/linear_search.py) |
| [Quicksort](https://en.wikipedia.org/wiki/Quicksort) | [\[X\]](quicksort/quicksort.c) | | | |


## Resources
Expand Down
59 changes: 59 additions & 0 deletions quicksort/quicksort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#include "stdio.h"

/*
* @ar_size array size
* @ar array pointer
*/
void quicksort(int ar_size, int * ar) {
int piv;
piv = ar[ar_size-1]; // chose last element as pivot
int i, temp, c = 0;
int prevmax, prevind = -1; // stores last number >= pivot

for (i=0; i<ar_size-1; i++){
if (ar[i] < piv){
if ((prevind > -1) && (ar[i] < prevmax)){
// swap current and previous large element
// current element is less than prevmax so move it to the left side
// and prevmax to the right side
temp = ar[i];
ar[i] = prevmax;
ar[prevind] = temp;
// prevind now has a less than pivot element, no need for it now
// therefore increment it for the next number
prevind = prevind + 1;
prevmax = ar[prevind];
}
c++; // pivot's final location (depends on count of items smaller than pivot)
}
else if (prevind < 0) {
// init first larger than pivot element
// it may be swapped out later (above block)
prevmax = ar[i];
prevind = i;
}
}

if (prevind > -1){ // if some swaps were done
ar[ar_size-1] = ar[c];
ar[c] = piv; // swap pivot to its correct position
}

if (ar_size > 2){
if (c != 0)
quicksort(c, &ar[0]); // recursively quicksort left partition
if (ar_size-c-1 != 0)
quicksort(ar_size-c-1, &ar[c+1]); // right partition
}
}

int main() {
int ar_size = 4, i;
int a[4] = {2, 3, 0, 4};
quicksort(ar_size, a);

for (i=0; i<ar_size; i++){
printf("%d\n", a[i]);
}
return 0;
}

0 comments on commit 02257d1

Please sign in to comment.