-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathquicksort-iterative.cpp
More file actions
75 lines (65 loc) · 1.47 KB
/
quicksort-iterative.cpp
File metadata and controls
75 lines (65 loc) · 1.47 KB
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
#include <stdio.h>
int partition (int arr[], int first, int h);
void quicksort (int arr[], int first, int last)
{
int memory[ last - first + 1 ];
int index = -1;
index++;
memory[ index ] = first;
index++;
memory[ index ] = last;
while ( index >= 0 )
{
last = memory[ index];
index--;
first = memory[ index];
index--;
int part_index = partition( arr, first, last );
if ( part_index-1 > first )
{
index++;
memory[ index ] = first;
index++;
memory[ index ] = part_index - 1;
}
if ( part_index+1 < last )
{
index++;
memory[ index ] = part_index + 1;
index++;
memory[ index ] = last;
}
}
}
int partition (int arr[], int first, int h)
{
int x = arr[h];
int i = (first - 1);
for (int j = first; j <= h- 1; j++){
if (arr[j] <= x){
i++;
int* s1 = &arr[i];
int* s2 = &arr[j];
int t = *s1;
*s1 = *s2;
*s2 = t;} }
int* s1 = &arr[i+1];
int* s2 = &arr[h];
int t = *s1;
*s1 = *s2;
*s2 = t;
return (i + 1);
}
int main()
{
int i,n,arr[1000];
printf("Enter size of array: ");
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d", &arr[i]);
}
quicksort( arr, 0, n - 1 );
for ( i = 0; i < n; i++ )
printf( "%d ", arr[i] );
return 0;
}