-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.c
More file actions
76 lines (62 loc) · 1.84 KB
/
BubbleSort.c
File metadata and controls
76 lines (62 loc) · 1.84 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
#include<stdio.h>
/**
O(n^2) sorting.
*/
void bubbleSort(int * list , int n)
{
if(list == NULL || n<2)
return;
int numOfSwaps=0;
int temp;
//In every iteration of this loop we will find next maximum; so only need to find N-1
//Maximums.
for(int i=0;i<n-1;i++)//[0] to [n-2] i.e. n-1 times
{
//numOfSwaps is to count the num of swaps; if 0 then it indicates that list is in non decreasing order and in that case we just return.
numOfSwaps = 0;
//Finding next maximum in only remaining list;
for(int j=0; j<n-1-i; j++) //[0 to n-2] to [0 to 0 in this 2nd last minimum will be selected]
{
// printf("Comparing %d with %d",list[j] ,list[j+1]);
//In bubble sort we simply compare with just next element
if(list[j]> list[j+1])
{
// printf(" Swapping. \n");
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
numOfSwaps++;
}
else{
// printf(" No Swapping \n");
}
}
if(numOfSwaps == 0)
{
// printf("Sorted after %d passes. ", i);
return;
}
}
//printf("Sorted after %d passes. ", n-1);
return;
}
/**
If getting compilation errors set -std=c99 in compiler options.
*/
/**
Uncomment commented printf for better understanding*/
int main()
{
int n; //Size of list to be sorted
scanf("%d", &n);
int a[n];
for(int i=0;i<n;i++)
scanf("%d",(a+i));
/**
Call the sort function.
*/
bubbleSort(a,n);
for(int i=0;i<n;i++)
printf("%d",*(a+i));
return 0;
}