C Bubble Sort

Bubble Sort for strings

Bubble Sort for strings


#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//from  w ww.j a  v  a  2  s.  co m
void bubble(char *items, int count);

int main(void)
{
  char s[255] = "asdfasdfasdfadsfadsf";
  bubble(s, strlen(s));
  printf("The sorted string is: %s.\n", s);

  return 0;
}


void bubble(char *items, int count)
{
  register int i, j;
  register char t;

  for(i = 1; i < count; ++i)
    for( j = count-1; j >= i; --j) {
      if(items[j - 1] > items[ j ]) {
        /* exchange elements */
        t = items[j - 1];
        items[j - 1] = items[ j ];
        items[ j ] = t;
      }
    }
}

A bubble sort on int array

A bubble sort on int array


#include<stdio.h>
/*w ww .j  av  a  2  s.  c  om*/
int bubble(int x[],int n) {
  int hold,j,pass,i,switched = 1;

  for(pass = 0; pass < n-1 && switched == 1;pass++) {
    switched=0;
    for (j=0;j<n-pass-1;j++)
        if (x[j]>x[j+1]) {
            switched=1;
            hold = x[j];
            x[j] = x[j+1];
            x[j+1]=hold;
        }
    }
    return(0);
}
int main() {
  int marks[10];
  int i;

  marks[0] = 39;
  marks[1] = 55;
  marks[2] = 43;
  marks[2] = 43;
  marks[3] = 49;
  marks[4] = 12;
  marks[5] = 2;
  marks[6] = 5;
  marks[7] = 4;
  marks[8] = 3;
  marks[9] = 1;
  bubble(marks, 10);

  for(i =0;i<10;i++){
      printf("%d ",marks[i]);
  }
}

Bubble sort with separate swap function

The following is another implementation for bubble sort. The only interesting part is that the swap function is defined separately.


#include <stdio.h>
#define MAX 10//from w  ww  .  j  a  v  a 2 s. c om

void swap(int *x,int *y){
   int temp;
   temp = *x;
   *x = *y;
   *y = temp;
}
void bsort(int list[]){
   int i,j;
   for(i=0;i<(MAX-1);i++){
      for(j=0;j<(MAX-(i+1));j++){
         if(list[j] > list[j+1]){
             swap(&list[j],&list[j+1]);
         }
      }
   }
}
void printlist(int list[]){
   int i;
   printf("The elements of the list are: \n");
   for(i=0;i<MAX;i++)
      printf("%d\t",list[i]);
}

void main(){
   int list[MAX];

   list[0] = 2; 
   list[1] = 1; 
   list[2] = 4; 
   list[3] = 3; 
   list[4] = 9;
   list[5] = 19; 
   list[6] = 17; 
   list[7] = 11; 
   list[8] = 5; 
   list[9] = 6;

   printf("The list before sorting is:\n");
   printlist(list);
   bsort(list);
   printf("The list after sorting is:\n");
   printlist(list);
}

The code above generates the following result.





















Home »
  C Language »
    Data Structures »




Data Structure
Algorithms