-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQUICK SORT ITERATIVE.cpp
80 lines (72 loc) · 1.84 KB
/
QUICK SORT ITERATIVE.cpp
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
//quick sort iterative
#include <bits/stdc++.h>
using namespace std;
int partition(int arr[], int start, int end)
{
int pivot = arr[end]; //rightmost element is the pivot
int pIndex = start;
//Is to push elements less than pivot to left and greater than to right of pivot
for (int i = start; i < end; ++i)
{
if (arr[i] < pivot)
{
swap(arr[i],arr[pIndex]);
pIndex++;
}
}
swap(arr[pIndex], arr[end]);
return pIndex;
}
void iterativeQuicksort(int arr[], int start, int end)
{
int stack[end - start + 1]; //Initializing stack size
int top = -1; //To keep track of top element in the stack
//pushing intial start and end
stack[++top] = start;
stack[++top] = end;
//pop till the stack is empty
while(top >= 0)
{
//poping the top two elements
//ie,poping parent subarray indexes to replace child subbary indexes
end = stack[top--];
start = stack[top--];
int pivot_index = partition(arr, start, end);
//Pushing the left subarray indexes that are less than pivot
if (pivot_index - 1 > start )
{
stack[++top] = start;
stack[++top] = pivot_index -1;
}
//pushing the right subarray indexes that are greater than pivot
if (pivot_index + 1 < end)
{
stack[++top] = pivot_index + 1;
stack[++top] = end;
}
}
}
void printArray(int arr[], int n)
{
cout<<"Sorted array is [ ";
for (int i = 0; i < n; ++i)
{
cout<<arr[i]<<" ";
}
cout<<"]"<<endl;
}
int main()
{
int n,i;
cout<<"Enter the number of elements you want to enter : \n";
cin>>n;
int arr[n];
cout<<"Enter the elements\n";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
iterativeQuicksort(arr,0,n-1);
printArray(arr, n);
return 0;
}