-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathOPtimizBubble_Sort.c
78 lines (69 loc) · 1.4 KB
/
OPtimizBubble_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
/*Bubble Sort Algorithm is the sorting algorithm in which each element is compared to its adjacent element
and if first elememt is greater than second element ,then the swapping occurs.
The swapping occurs till the array is sorted.
*/
#include <stdio.h>
#include <stdbool.h>
void swap(int *, int *);
bool optimised_bubble(int[], int);
int main()
{
int size, arr[size], temp;
//Reading Input
printf("Input :\n");
printf("Enter the size of an array : \n");
scanf("%d", &size);
printf("Enter the elements of an array :\n");
for (int index = 0; index < size; index++)
{
scanf("%d", &arr[index]);
}
optimised_bubble(arr, size);
//Displaying Output
printf("Output :\n");
printf("The sorted array is :\n");
for (int index = 0; index < size; index++)
{
printf("%d ", arr[index]);
}
return 0;
}
// Function to sort the array in an optimised way
bool optimised_bubble(int arr[], int size)
{
int index;
bool sort = true;
for (int index = 0; index < size; index++)
{
for (int j = 0; j < size - 1 - index; j++)
{
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
sort = false;
}
}
if (sort)
{
break;
}
}
}
// Function to swap two numbers
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/*
Input:
Enter the size of an array: 5
Enter the elements of an array :
7 9 8 2 4
Output :
2 4 7 8 9
Time Complexity : O(n)
Space Complexity : O(1)
*/