Skip to content

Commit fedd7f6

Browse files
authored
updates with different pivot - clrs
1 parent 09b1581 commit fedd7f6

File tree

1 file changed

+71
-30
lines changed

1 file changed

+71
-30
lines changed

recursion 2/quick sort code

Lines changed: 71 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,82 @@
1-
void swap(int *a,int *b)
1+
2+
void swap(int *a, int *b)
3+
{
4+
int temp = *a;
5+
*a = *b;
6+
*b = temp;
7+
}
8+
int p_front_cn(int a[], int l , int h )// equal to the left
9+
{
10+
int pivot = a[l];
11+
int count = 0;
12+
for (int i = l + 1 ; i <= h; i++)
13+
{if (a[i] <= pivot) count++; }
14+
15+
swap(&a[l], &a[l + count]);
16+
pivot = a[l + count];
17+
int i = l ; int j = l + count + 1;
18+
while (i < l + count && j <= h)
19+
{
20+
if (a[i] <= pivot)i++;
21+
else if (a[j] > pivot)j++;
22+
else
23+
{
24+
swap ( &a[i] , &a[j]); i++ ; j++;
25+
}
26+
}
27+
return l + count;
28+
}
29+
int p_back_clrs(int a[], int l , int h)
230
{
3-
int temp=*a;
4-
*a=*b;
5-
*b=temp;
31+
int pivot = a[h];
32+
int i = l - 1;
33+
for (int j = l ; j < h ; j++)
34+
{
35+
if (a[j] < pivot)
36+
{
37+
i++;
38+
swap(&a[j], &a[i]);
39+
}
40+
}
41+
swap(&a[h], &a[i + 1]);
42+
return i + 1;
643
}
44+
int p_front_clrs(int a[] , int l , int h)
45+
{
46+
int pivot = a[l];
47+
48+
int i = h + 1;
49+
50+
for (int j = h; j > l ; j--)
51+
{
52+
if (a[j] > pivot)
53+
{
54+
i--;
55+
swap(&a[j], &a[i]);
56+
}
57+
}
58+
swap(&a[l] , &a[i - 1]);
59+
return i - 1;
760

8-
int partition (int arr[], int low, int high)
9-
{
10-
int pivot = arr[high]; // pivot
11-
int i = (low - 1); // Index of smaller element
12-
13-
for (int j = low; j <= high - 1; j++)
14-
{
15-
// If current element is smaller than the pivot
16-
if (arr[j] < pivot)
17-
{
18-
i++; // increment index of smaller element
19-
swap(&arr[i], &arr[j]);
20-
}
21-
}
22-
swap(&arr[i + 1], &arr[high]);
23-
return (i + 1);
24-
}
25-
void QuickSort(int a[],int s,int e)
61+
}
62+
void QuickSort(int a[], int s, int e)
2663
{
27-
if(s>=e)
28-
return;
29-
int p=partition(a,s,e);
30-
QuickSort(a,s,p-1);
31-
QuickSort(a,p+1,e);
64+
if (s >= e)
65+
return;
66+
//int p = p_front_cn(a, s, e);
67+
//int p = p_front_clrs(a, s, e);
68+
int p = p_back_clrs(a, s, e);
69+
70+
QuickSort(a, s, p - 1);
71+
QuickSort(a, p + 1, e);
72+
3273

3374
}
3475
void quickSort(int input[], int size) {
3576

36-
int start = 0;
37-
int end = size-1;
77+
int start = 0;
78+
int end = size - 1;
3879

39-
QuickSort(input,start,end);
80+
QuickSort(input, start, end);
4081

4182
}

0 commit comments

Comments
 (0)