forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble_sort.c
More file actions
66 lines (54 loc) · 1.25 KB
/
bubble_sort.c
File metadata and controls
66 lines (54 loc) · 1.25 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
55
56
57
58
59
60
61
62
63
64
65
66
/*
* Program: Bubble Sort Algorithm
*
* Problem Statement:
* Implement bubble sort to sort an array of integers in ascending order.
*
* Input/Output Example:
* Enter the number of elements: 5
* Enter 5 integers: 64 34 25 12 22
* Original array: 64 34 25 12 22
* Sorted array: 12 22 25 34 64
*
* Time Complexity: O(n²)
* Space Complexity: O(1)
*
* Compile: gcc bubble_sort.c -o bubble_sort
*/
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Original array: ");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}