-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbubble_sort.c
65 lines (62 loc) · 1.63 KB
/
bubble_sort.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
#include <stdio.h>
void printArray(int *A, int n)
{
for (int i = 0; i < n; i++)
{
printf("%d ", A[i]);
}
printf("\n");
}
void bubbleSort(int *A, int n)
{
int temp;
int isSorted = 0;
for (int i = 0; i < n - 1; i++) // For number of pass
{
printf("Working on pass number %d\n", i + 1);
for (int j = 0; j < n - 1 - i; j++) // For comparison in each pass
{
if (A[j] > A[j + 1])
{
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
void bubbleSortAdaptive(int *A, int n)
{
int temp;
int isSorted = 0;
for (int i = 0; i < n - 1; i++) // For number of pass
{
printf("Working on pass number %d\n", i + 1);
isSorted = 1;
for (int j = 0; j < n - 1 - i; j++) // For comparison in each pass
{
if (A[j] > A[j + 1])
{
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
isSorted = 0;
}
}
if (isSorted)
{
return;
}
}
}
int main()
{
// int A[] = {12, 54, 65, 7, 23, 9};
int A[] = {1, 2, 5, 6, 12, 54, 625, 7, 23, 9, 987};
// int A[] = {1, 2, 3, 4, 5, 6};
int n = 11;
printArray(A, n); // Printing the array before sorting
bubbleSort(A, n); // Function to sort the array
printArray(A, n); // Printing the array before sorting
return 0;
}