-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #33 from rattle99/master
add quicksort
- Loading branch information
Showing
2 changed files
with
77 additions
and
13 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
/*Program for quick sort implementation in C++. */ | ||
|
||
#include <iostream> | ||
#include <vector> | ||
|
||
int partition(std::vector<int> &A, int start, int end) | ||
{ | ||
int temp; | ||
int pivot = A[end]; | ||
int partitionIndex = start; // set partition index as start initially | ||
for(int i=start; i<end; i++) | ||
{ | ||
if(A[i] <= pivot) | ||
{ | ||
temp=A[i]; | ||
A[i]=A[partitionIndex]; | ||
A[partitionIndex]=temp; | ||
partitionIndex++; | ||
} | ||
} | ||
temp=A[partitionIndex]; // Swap pivot element | ||
A[partitionIndex]=A[end]; // eith element at | ||
A[end]=temp; // partition index | ||
|
||
return partitionIndex; | ||
} | ||
|
||
std::vector<int> quick_sort(std::vector<int> &A, int start, int end) | ||
{ | ||
/* std::cout<<"Current list : \n"; | ||
for(int i=0;i<A.size();i++) | ||
{ | ||
std::cout<<A[i]<<" "; | ||
} | ||
std::cout<<"\nSorted list : \n"; | ||
*/ | ||
|
||
if(start<end) | ||
{ | ||
int partitionIndex = partition(A,start,end); | ||
quick_sort(A,start,partitionIndex-1); | ||
quick_sort(A,partitionIndex+1, end); | ||
} | ||
|
||
/* for(int i=0;i<A.size();i++) | ||
{ | ||
std::cout<<A[i]<<" "; | ||
} | ||
*/ return A; | ||
} | ||
|
||
int main() | ||
{ | ||
std::cout<<"\nTest\n"; | ||
std::vector<int> arr={10,2,23,-4,235,56,2,6,5,5,5,23,-4,346,-56,81,43,654,435,-54}; | ||
quick_sort(arr, 0, arr.size()-1); | ||
std::cout<<"\n\n\n"; | ||
for(int i=0;i<arr.size();i++) | ||
{ | ||
std::cout<<arr[i]<<" "; | ||
} | ||
return 0; | ||
} | ||
|
This file contains 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