-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble_sort.c
86 lines (62 loc) · 1.35 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
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
// If at any Pass no Swapping is done, Then it is sure that array has already fully sorted.
#include<stdio.h>
#include<stdbool.h>
void print_array(int a[],int n)
{
printf("[");
for(int i=0;i<n;i++)
{
printf("%d",a[i]);
if(i!=n-1)
printf(" ");
}
printf("]");
}
int * bubble_sort(int a[],int n)
{
bool mustContinue=true;
int temp,i,j;
for(i=0;i<n;i++)
{
if(!mustContinue)
{
if(i==1)
printf("(The Array is Already Sorted)\n");
break;
}
mustContinue=false;
printf("The Array After %d Iteration(s) is:",i+1);
print_array(a,n);
printf("\n");
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
mustContinue=true;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
return a;
}
int main()
{
int arr[1000],n,*ptr;
printf("Enter the Number of Elements:");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
printf("Enter The %d-th Element:",i+1);
scanf("%d",&arr[i]);
}
printf("\n");
printf("The Array Before Sorting:\n");
print_array(arr,n);
printf("\n\n");
ptr=bubble_sort(arr,n);
printf("\n\nThe Array After Sorting:\n");
print_array(ptr,n);
return 0;
}