-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqsort.c
More file actions
94 lines (77 loc) · 2.13 KB
/
qsort.c
File metadata and controls
94 lines (77 loc) · 2.13 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* quicksort takes parameters:
1. *base - base of array (pointer pointing to first element of array)
2. number of elements to be sorted
3. size of each element (to allow memory allocaion)
4. compare function - each with a different prototype that we create
*/
int compareInt(const void* p1, const void* p2){
/*
return -1 if p < q
return 0 if p = q
return 1 if p > q
*/
// the order is always -1, 0, 1 so if we appoint 1 to > and -1 to < then it will be descending order
// we need to type cast the void pointers (with const!!! as we should not change values)
const int *p = p1;
const int *q = p2;
if(*p < *q){
return -1;
}
if(*p == *q){
return 0;
}
if(*p > *q){
return 1;
}
}
int strCompare(const void* s1, const void* s2){
const char** p = s1; // since hey are 2D arrays hence a double pointer
const char** q = s2;
if(strcmp(*p, *q) < 0){
return -1;
}
if(strcmp(*p, *q) == 0){
return 0;
}
if(strcmp(*p, *q) > 0){
return 1;
}
}
int main(){
int array[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
qsort(array, 10, sizeof(int), compareInt);
// we do not need to pass arguments for compareInt as its a fucntion pointer (address)
int i = 0;
while(i < 10){
printf("%d\t", array[i]);
i++;
}
// for strings
char **str; // double pointer (pointer to a pointer)
str = malloc(10 * sizeof(char *)); // size of character array
// creates pointer to a pointer hence array of 10 pointers
// basically creates a dymnamic 2D array as each pointer is to a character in string
int j = 0;
while(j < 3){
char* temp = malloc(100 * sizeof(char));
scanf("%s", temp);
str[j] = temp;
j++;
}
j = 0;
while(j < 3){
printf("%s\t", str[j]);
j++;
}
qsort(str, 3, sizeof(char*), strCompare);
printf("\nafter qsort:\n");
j = 0;
while(j < 3){
printf("%s\t", str[j]);
j++;
}
return 0;
}