Sunday, 14 December 2014

Pin It

Widgets

Iterative BubbleSort for Array of Integers


#include<stdio.h>
/*
* Implemented by Arjun Sunel.
*/

// Method to swap two integers by reference.
void Swap(int *first, int *second)
{
 int temp = *first;
 *first = *second;
 *second = temp;
}

// Bubble Sort Method
void BubbleSort(int array[], int size)
{
 int i, j;
 int swapped = 1;
 
 for(i = 0; swapped && i < size - 1; i++)
 {
  swapped = 0;
  for(j = 0; j < size - 1 - i; j++)
  {
   if( array[j] > array[j + 1] )
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
 int array[] = {5, -12, 14, 7};
 int arraySize = 4;
 int index;
  
 printf("Before sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 BubbleSort(array, arraySize);

 printf("\nAfter sorting : \n");
 for(index = 0; index <= arraySize - 1; index++)
 {
  printf("%d ", array[index]);
 } 
 
 printf("\n");
}


No comments: