forked from SN786/Cplusplus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSort.c
57 lines (49 loc) · 1.04 KB
/
BubbleSort.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
//implements bubble sort
#include <stdio.h>
#include <stdlib.h>
void printArray(int *arr, int n)
{
int i;
printf("{");
for(i=0; i<n; ++i)
printf(" %d", *(arr+i));
printf(" }");
}
void bubbleSort(int *arr, int n)
{
int i, j, temp;
for(i=0; i<n; ++i)
{
for(j=0; j<n-i-1; ++j)
{
if (*(arr+j+1) < *(arr+j))
{
temp = *(arr+j);
*(arr+j) = *(arr+j+1);
*(arr+j+1) = temp;
}
}
}
}
int main()
{
int n, i;
do
{
printf("\nEnter the number of elements in the array\n");
scanf("%d", &n);
}
while (n<1);
int *arr = (int *)calloc(n, sizeof(int));
for(i=0; i<n; ++i)
{
printf("\nEnter element %d\n", i+1);
scanf("%d", arr+i);
}
printf("\nDisplaying original array...");
printArray(arr, n);
bubbleSort(arr, n);
printf("\nDisplaying sorted array...");
printArray(arr, n);
return 0;
}