1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std; //NECESSARY FOR MAIN PART
std::size_t partition (int *data, std::size_t total_size, std::size_t &pivot_Index)
{
//IF ARRAY CONSIST ONLY ONE
if(total_size==1) return 0;
//ALL THE OTHER POSSIBLE CASES
//Creating a pointers to track the left and right
size_t left_ptr=0;
size_t right_ptr=total_size-2;
std::srand(std::time(NULL));
pivot_Index= random() % total_size;
//PUT THE PIVOT AT THE VERY END OF THE ARRAY
std::swap(data[total_size-1],data[pivot_Index]);
//NOW COMPARE AND SWAP
while(left_ptr != right_ptr)
{
if(data[left_ptr]<= data[total_size-1])
{
left_ptr++; continue;
}
if(data[right_ptr] > data[total_size-1])
{
right_ptr--; continue;
}
std::swap(data[left_ptr],data[right_ptr]);
}
std::swap(data[left_ptr],data[total_size-1]);
return left_ptr;
}
void quicksort(int *data, std::size_t total_size)
{
if(total_size==0) return;
std::size_t pivotIndex,left_sub_arr_size, right_sub_arr_size;
//Partition the array and set the pivot index.
size_t updated_pivot= partition(data,total_size,pivotIndex);
//Compute size of sub- arrays
left_sub_arr_size= updated_pivot;
right_sub_arr_size=total_size-left_sub_arr_size-1;
//Sort the left and right
quicksort(data, left_sub_arr_size);
quicksort((data+left_sub_arr_size+1), right_sub_arr_size);
}
int main()
{
try{
const size_t SIZE=10;
int arr[SIZE]={10,9,8,7,6,5,4,3,2,1};
quicksort(arr, SIZE);
for(int i=0; i<SIZE; ++i)
cout<<arr[i]<<"\t";
cout<<endl;
}
catch(exception& e)
{
cout<<"Exception has occured: "<<e.what()<<endl;
}
}
|