forked from NITSkmOS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This adds Bubble Sort algorithm written in C. Closes NITSkmOS#19
- Loading branch information
Showing
2 changed files
with
48 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
#include <stdio.h> | ||
|
||
void bubble_sort(int[], int); | ||
void print_array(int[], int); | ||
void swap(int*, int*); | ||
|
||
int main() { | ||
int arr[] = {45, 92, 54, 23, 6, 4, 12}; | ||
int n = sizeof(arr) / sizeof(arr[0]); | ||
bubble_sort(arr, n); | ||
printf("Sorted array: \n"); | ||
print_array(arr, n); | ||
} | ||
|
||
/* Function to swap two numbers */ | ||
void swap(int *a, int *b) { | ||
int temp = *a; | ||
*a = *b; | ||
*b = temp; | ||
} | ||
|
||
/* Bubble Sort algorithm */ | ||
void bubble_sort(int arr[], int n) { | ||
int i, j; | ||
int swapped; | ||
for (i = 0; i < n - 1; ++i) { | ||
swapped = 0; | ||
for (j = 0; j < n - i - 1; ++j) { | ||
if (arr[j] > arr[j+1]) { | ||
swap(&arr[j], &arr[j+1]); | ||
swapped = 1; | ||
} | ||
} | ||
|
||
/* If no two elements are swapped by inner loop, then break */ | ||
if (swapped == 0) | ||
break; | ||
} | ||
} | ||
|
||
/* Function to print array */ | ||
void print_array(int arr[], int size) { | ||
int i; | ||
for (i = 0; i < size; i++) | ||
printf("%d ", arr[i]); | ||
printf("\n"); | ||
} |