forked from randerson112358/C-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSort3.c
103 lines (79 loc) · 1.96 KB
/
BubbleSort3.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
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
This program sorts an array of elements using the bubble sort algorithm
By: randerson112358
This procedure of bubble sort Best Case is O(n) and Worst Case is O(n^2)
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
*/
#include <stdio.h>
int BubbleSort(int size, int *array);
int main(void){
int size, i, array[20];
printf("Enter total number(s) of elements: ");
scanf("%d", &size);
printf("Enter the %d elements: ", size);
for(i=0; i<size; i++)
{
scanf("%d", &array[i]);
}
//Run the Bubble Sort Algorithm to sort the list of elements
BubbleSort(size, array);
printf("After Sorting: ");
for(i=0; i<size; i++)
{
printf(" %d", array[i]);
}
printf("\n");
system("pause"); // uncomment if you are not using Windows OS
return 0;
}
/*
This procedure of bubble sort Best Case is O(n) and Worst Case is O(n^2)
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
*/
int BubbleSort(int size, int *array){
int swapped = 0; //0=false and 1= true
int i, temp;
int n = size;
do{
//Set swapped to false
swapped = 0;
for(i=1; i<= n-1; i++)
{
//If the previous element is greater than the next element swap them
if(array[i-1] > array[i])
{
//Swap
temp = array[i-1];
array[i-1] = array[i];
array[i]= temp;
//Set swapped to true
swapped = 1;
}
}
}while(swapped== 1);
return 0;
}