-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuick-Sort-code.c
90 lines (70 loc) · 1.44 KB
/
Quick-Sort-code.c
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
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
int n = 5;
/* Write the function for quick sort using C.*/
// Function for pivot
int pivot(int *a, int first, int last);
// Function for swap
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
// Function for Quick Sort
void quickSort( int *a, int first, int last)
{
int pivotElement;
if (first < last)
{
pivotElement = pivot(a, first, last);
for (int i = 0; i < n; i++)
{
printf("%d\t", *(a + i));
}
printf("\n");
quickSort(a, first, pivotElement - 1);
quickSort(a, pivotElement + 1, last);
}
}
// Function for pivot
int pivot(int *a, int first, int last)
{
int p = first;
int pivotElement = a[first];
for (int i = first + 1 ; i <= last ; i++)
{
if (a[i] <= pivotElement)
{
p++;
//swap(a[i], a[p]);
int temp = a[i];
a[i] = a[p];
a[p] = temp;
}
}
// swap(a[p], a[first]);
int temp = a[p];
a[p] = a[first];
a[first] = temp;
return p;
}
// Main function
void main()
{
int *arr, n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
arr = (int *)calloc(n, sizeof(int));
for (i = 0; i < n; i++)
{
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
}
printf("Sorted array is: ");
quickSort (arr, 0, n - 1);
for (i = 0; i < n; i++)
{
printf("%d\t ", arr[i]);
}
}