Skip to content

Commit 54a62e3

Browse files
committed
added quick sort algorithm
1 parent 48a0661 commit 54a62e3

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

quicksort.cpp

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
2+
/* C implementation QuickSort */
3+
#include<iostream>
4+
using namespace std;
5+
6+
// A utility function to swap two elements
7+
void swap(int* a, int* b)
8+
{
9+
int t = *a;
10+
*a = *b;
11+
*b = t;
12+
}
13+
14+
/* This function takes last element as pivot, places
15+
the pivot element at its correct position in sorted
16+
array, and places all smaller (smaller than pivot)
17+
to left of pivot and all greater elements to right
18+
of pivot */
19+
int partition (int arr[], int low, int high)
20+
{
21+
int pivot = arr[high]; // pivot
22+
int i = (low - 1); // Index of smaller element
23+
24+
for (int j = low; j <= high- 1; j++)
25+
{
26+
// If current element is smaller than or
27+
// equal to pivot
28+
if (arr[j] <= pivot)
29+
{
30+
i++; // increment index of smaller element
31+
swap(&arr[i], &arr[j]);
32+
}
33+
}
34+
swap(&arr[i + 1], &arr[high]);
35+
return (i + 1);
36+
}
37+
38+
/* The main function that implements QuickSort
39+
arr[] --> Array to be sorted,
40+
low --> Starting index,
41+
high --> Ending index */
42+
void quickSort(int arr[], int low, int high)
43+
{
44+
if (low < high)
45+
{
46+
/* pi is partitioning index, arr[p] is now
47+
at right place */
48+
int pi = partition(arr, low, high);
49+
50+
// Separately sort elements before
51+
// partition and after partition
52+
quickSort(arr, low, pi - 1);
53+
quickSort(arr, pi + 1, high);
54+
}
55+
}
56+
57+
/* Function to print an array */
58+
void printArray(int arr[], int size)
59+
{
60+
int i;
61+
for (i=0; i < size; i++)
62+
cout<<arr[i];
63+
cout<<"\n";
64+
}
65+
66+
// Driver program to test above functions
67+
int main()
68+
{
69+
int arr[] = {10, 7, 8, 9, 1, 5};
70+
int n = sizeof(arr)/sizeof(arr[0]);
71+
quickSort(arr, 0, n-1);
72+
cout<< "Sorted array: \n";
73+
printArray(arr, n);
74+
return 0;
75+
}

0 commit comments

Comments
 (0)