Sunday, 14 December 2014

Pin It

Widgets

Iterative BubbleSort for Array of Strings


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

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

// Bubble Sort Method
void BubbleSort(char *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(strcmp(array[j], array[j+1]) > 0)
   {
    Swap(&array[j], &array[j + 1]);
    swapped = 1;
   }
  }
 }
}

// Entry point of the program
int main()
{
 char* array[] = {"dog", "dose", "apple", "baby", "den", "deck"};
 int arraySize = 6;
 int index;

 printf("Before Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 }  

 printf("\n");
 
 BubbleSort(array, arraySize);
 printf("After Sorting : \n");
 for(index = 0; index < arraySize; index++)
 {
  printf("%s ", array[index]);
 } 
 
 return 0;
}



No comments: