Skip to content

Commit

Permalink
bubble_sort.c: Add Bubble Sort in C
Browse files Browse the repository at this point in the history
This adds Bubble Sort algorithm written in C.

Closes NITSkmOS#19
  • Loading branch information
123vivekr committed Oct 2, 2018
1 parent 27f8287 commit 257c37e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ This repository contains examples of various algorithms written on different pro
| [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) | | | | [:octocat:](counting_sort/Python) |
| [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | | | [:octocat:](radix_sort/Python) |
| [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) |
| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | | [:octocat:](bubble_sort/Cpp) | | |
| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | |
| [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | | | | [:octocat:](shell_sort/Python) |


Expand Down
47 changes: 47 additions & 0 deletions bubble_sort/C/bubble_sort.c
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");
}

0 comments on commit 257c37e

Please sign in to comment.