Last active
October 20, 2017 05:55
-
-
Save dhruvappstack/41a2b3a62b9786fccc5ba193266bba9c to your computer and use it in GitHub Desktop.
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| using namespace std; | |
| int getPartitionPoint(int* arrData, int low, int high){ | |
| //Set pivot | |
| int pivot = arrData[(low+high)/2]; | |
| while(low < high){ | |
| //Move pointer for left half | |
| while(arrData[low] < pivot){ | |
| low++; | |
| } | |
| //Move pointer for right half | |
| while(arrData[high] > pivot){ | |
| high--; | |
| } | |
| //Edge case | |
| if (arrData[low] == arrData[high]){ | |
| low++; | |
| }else{ | |
| //Swap if out of order | |
| if(low < high){ | |
| int temp = arrData[low]; | |
| arrData[low] = arrData[high]; | |
| arrData[high]= temp; | |
| } | |
| } | |
| } | |
| // Return partition point | |
| return high; | |
| } | |
| void quickSort(int* arrData,int low ,int high){ | |
| if(low < high){ | |
| //Partition array | |
| int partitionIndex = getPartitionPoint(arrData,low,high); | |
| //Sort left half | |
| quickSort(arrData,low,partitionIndex-1); | |
| //Sort right half | |
| quickSort(arrData,partitionIndex+1,high); | |
| } | |
| } | |
| int main(){ | |
| int arrData[] = { | |
| 1231,12,2233,32323,23}; | |
| int size = sizeof(arrData)/sizeof(arrData[0]); | |
| quickSort(arrData,0,size-1); | |
| for(int i = 0;i< size;i++){ | |
| cout<<" "<<arrData[i]; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment