forked from Dipak3007/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandomized_quick_sort.c
More file actions
68 lines (66 loc) · 1.22 KB
/
randomized_quick_sort.c
File metadata and controls
68 lines (66 loc) · 1.22 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
#include <stdio.h>
#include <stdlib.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int randomizedpartion(int *arr, int *p, int *r)
{
int pivotIndex = *p + rand() % (*r - *p + 1);
int pivot;
int i = *p - 1;
int j;
pivot = arr[pivotIndex];
swap(&arr[pivotIndex], &arr[*r]);
for (j = *p; j < *r; j++)
{
if (arr[j] < pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[*r]);
return i + 1;
}
void randomizedquicksort(int *arr, int *p, int *r)
{
int j;
if (*p < *r)
{
j = randomizedpartion(arr, p, r);
int a = j - 1;
int b = j + 1;
randomizedquicksort(arr, p, &a);
randomizedquicksort(arr, &b, r);
}
}
void printelement(int *arr, int size)
{
printf("Sorted Array: ");
for (int i = 0; i <= size - 1; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
{
int size;
printf("Enter the size of the array: \n");
scanf("%d", &size);
int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i <= size - 1; i++)
{
printf("Enter element %d \n", i + 1);
scanf("%d", &arr[i]);
}
printf("\n");
int a = 0;
int b = size - 1;
randomizedquicksort(arr, &a, &b);
printelement(arr, size);
}