forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble-sort.c
60 lines (52 loc) · 1.15 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
//bubble sort
#include <stdio.h>
#include <stdlib.h>
void swap(int *value1, int *value2);
void bubble_sort(int array[], int array_size)
{
for(int i = 0; i < array_size; i++)
{
for(int j = 0; j < array_size - 1; j++)
{
if(array[j] > array[j+1])
{
swap(&array[j], &array[j+1]);
}
}
}
}
void swap(int *value1, int *value2)
{
int temp = *value1;
*value1 = *value2;
*value2 = temp;
}
int main()
{
int array_size;
do{
printf("Input the size of the array: ");
scanf("%d", &array_size);
}while(array_size <= 1);
int *array = (int*)malloc(sizeof(int)*array_size);
for(int i = 0; i < array_size; i++)
{
printf("Input an integer: ");
scanf("%d", &array[i]);
}
bubble_sort(array, array_size);
printf("Sorted array: [ ");
for(int i = 0; i < array_size; i++)
{
printf("%d ", array[i]);
}
printf("]\n");
return 0;
}
/*
* Input the size of the array: 5
* Input 5 integers: [ 28, 17, 2, 5, 43 ]
* Output: Sorted array: [ 2, 5, 17, 28, 43 ]
*
* Time complexity: O(n^2)
*/