-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathbubble_sort.cx
More file actions
54 lines (43 loc) · 1.39 KB
/
Copy pathbubble_sort.cx
File metadata and controls
54 lines (43 loc) · 1.39 KB
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
//! Unsorted Array:\n64 34 25 12 22 11 90 \nSorted Array in Ascending Order:\n11 12 22 25 34 64 90 \n
include <stdio.h>
// Function to perform an optimized bubble sort
void bubbleSort(int[] arr, int n) {
int temp;
bool swapped;
// Outer loop for the number of passes
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Inner loop for adjacent element comparisons
// n - i - 1 ensures we ignore already sorted elements at the end
for (int j = 0; j < n - i - 1; j++) {
if arr[j] > arr[j + 1] {
// Swap arr[j] and arr[j + 1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true; // Set flag to true if swap occurs
}
}
// If no two elements were swapped by inner loop, then break
if !swapped {
break;
}
}
}
// Function to print the array
void printArray(int[] arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int[] data = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Array:\n");
printArray(data, n);
bubbleSort(data, n);
printf("Sorted Array in Ascending Order:\n");
printArray(data, n);
return 0;
}