Showing posts with label Program in C using Bubble Sort. Show all posts
Showing posts with label Program in C using Bubble Sort. Show all posts

Sunday, October 7, 2012

Bubble sort in string array


/******<soeasyprograms.blogspot.in>*****/
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 50
#define N 2000
void sort_words(char *x[], int y);
void swap(char **, char **);
int main(void)
{
char word[MAX];
char *x[N];
int n = 0;
int i = 0;
for(i = 0; scanf("%s", word) == 1; ++i)
{
if(i >= N)
printf("Limit reached: %d\n", N), exit(1);
x[i] = calloc(strlen(word)+1, sizeof(char));
strcpy(x[i], word);
}
n = i;
sort_words(x, n);
for(i = 0; i < n; ++i)
printf("%s\n", x[i]);
return(0);
}
void sort_words(char *x[], int y)
{
int i = 0;
int j = 0;
for(i = 0; i < y; ++i)
for(j = i + 1; j < y; ++j)
if(strcmp(x[i], x[j]) > 0)
swap(&x[i], &x[j]);
}
void swap(char **p, char **q)
{
char *tmp;
tmp = *p;
*p = *q;
*q = tmp;
}

Tuesday, April 10, 2012

Program in C using Bubble Sort


/***********<soeasyprograms.blogspot.in>***********/
// Program of sorting using bubble sort method
#include <stdio.h>

#define MAX 20

main()
Sort
{
  int arr[MAX],i,j,k,temp,n,xchanges;
  printf("Enter the number of elements : ");
  scanf("%d",&n);
  for (i = 0; i < n; i++)
  {
    printf("Enter element %d : ",i+1);
    scanf("%d",&arr[i]);
  }
  printf("Unsorted list is :\n");
  for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
   printf("\n");

/* Bubble sort*/
  for (i = 0; i < n-1 ; i++)
  {
    xchanges=0;
    for (j = 0; j <n-1-i; j++)
    {
      if (arr[j] > arr[j+1])
      {
        temp = arr[j];
        arr[j] = arr[j+1];
        arr[j+1] = temp;
        xchanges++;
      }/*End of if*/
    }/*End of inner for loop*/
    if(xchanges==0) /*If list is sorted*/
      break;
    printf("After Pass %d elements are :  ",i+1);
    for (k = 0; k < n; k++)
      printf("%d ", arr[k]);
    printf("\n");
  }/*End of outer for loop*/

  printf("Sorted list is :\n");
  for (i = 0; i < n; i++)
    printf("%d ", arr[i]);
  printf("\n");
}/*End of main()*/


Output of this Program is: