-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion6.c
44 lines (36 loc) · 887 Bytes
/
question6.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
/*
BUBBLE SORT
Elements are compared in pairs to see if they are sorted, if not they are swapped
In each iteration one greatest element moves to its correct position.
It can be remembered as in each iteration the bubble(largest element) comes to the top (last in array)
Time Complexity:
Best case: O(n) -- already sorted just checking by looping once or for value very less than n
Worst case: O(n^2) -- nested loop
Space Complexity:
O(1)
*/
#include <stdio.h>
#include <math.h>
int main(){
int a[] = {9,6,5,4,0,7,3,5,11};
int length = sizeof(a)/sizeof(a[0]);
int swapped,i,j;
for(i=0; i<length;i++){
swapped = 0;
for(j=0;j<length-i-1;j++){
if(a[j] > a[j+1]){
int temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
swapped = 1;
}
}
if(swapped == 0){
break;
}
}
printf("sorted array is\n");
for(int z=0; z<length; z++){
printf("%d ", a[z]);
}
}