Friday, November 21, 2014

C Bubble pro



Program to sort set of strings in alphabetical order

#include
#include
void main()
{
   char s[5][20], t[20];
   int i, j;
   clrscr();
   printf("\nEnter any five strings : ");
   for (i = 0; i < 5; i++)
      scanf("%s", s[i]);
    for (i = 1; i < 5; i++)
    {
      for (j = 1; j < 5; j++)
      {
         if (strcmp(s[j - 1], s[j]) > 0)
          {
            strcpy(t, s[j - 1]);
            strcpy(s[j - 1], s[j]);
            strcpy(s[j], t);
         }
      }
   }
   printf("\nStrings in order are : ");
   for (i = 0; i < 5; i++)
      printf("\n%s", s[i]);
    getch();
}

Output

Enter any five strings :
pri
pra
pru
pry
prn
Strings in order are :
pra
pri
prn
pru
pry

C Program to Implement Bubble Sort in C Programming


#include
#include
 void bubble_sort(int[], int);

void main()
{
   int arr[30], num, i;
   printf("\nEnter no of elements :");
   scanf("%d", &num);
   printf("\nEnter array elements :");
   for (i = 0; i < num; i++)
   scanf("%d", &arr[i]);
   bubble_sort(arr, num);
   getch();
}
void bubble_sort(int iarr[], int num)
{
   int i, j, k, temp;
   printf("\nUnsorted Data:");
   for (k = 0; k < num; k++)
  {
      printf("%5d", iarr[k]);
   } 
   for (i = 1; i < num; i++)
   {
      for (j = 0; j < num - 1; j++)
       {
         if (iarr[j] > iarr[j + 1])
          {
            temp = iarr[j];
            iarr[j] = iarr[j + 1];
            iarr[j + 1] = temp;
         }
      }
       printf("\nAfter pass %d : ", i);
      for (k = 0; k < num; k++)
      {
         printf("%5d", iarr[k]);
      }
   }
}

C Program to Sort Structures on the basis of Structure Element


#include
#include 
struct cricket
{
   char pname[20];
   char tname[20];
   int avg;
}
player[10], temp; 
void main()
{
   int i, j, n;
   clrscr();
   for (i = 0; i < 10; i++)
     {
      printf("\nEnter Player Name : ");
      scanf("%s", player[i].pname);
      printf("\nEnter Team Name : ");
      scanf("%s", player[i].tname);
      printf("\nEnter Average : ");
      scanf("%d", &player[i].avg);
      printf("\n");
   }
   n = 10;
   for (i = 1; i < n; i++)
      for (j = 0; j < n - i; j++)
       {
         if (strcmp(player[j].tname, player[j + 1].tname) > 0)
          {
            temp = player[j];
            player[j] = player[j + 1];
            player[j + 1] = temp;
         }
      }
   for (i = 0; i < n; i++)
     {
      printf("\n%s\t%s\t%d",player[i].pname,player[i].tname,player[i].avg);
   }
   getch();
}

Output

Enter Player Name : Sehwag
Enter Team Name : India
Enter Average : 78

Enter Player Name : Ponting
Enter Team Name : Australia
Enter Average : 65

Enter Player Name : Lara
Enter Team Name : WI
Enter Average : 67

Ponting Australia  65
Sehwag  India      78
Lara    WI         67

No comments:

Post a Comment