[C/C++] Program to Sort Array – Bubble Sorting

C/C++ code to arrange number in ascending or descending order using bubble sorting algorithm. In bubble sorting 1st element is compared with 2nd element and then swapped. Similarly 2nd with 3rd and then 3rd with 4th and so on.. Unless the array is sorted.

C Code

#include <stdio.h>
 
int main()
{
  int array[100], temp, n;
 
  printf("Enter number of elements\n");
  scanf("%d", &n);
 
  printf("Enter %d integers\n", n);
 
  for (int i = 0; i < n; i++)
    scanf("%d", &array[i]);
 
  for (int i = 0 ; i < ( n - 1 ); i++)
  {
    for (int j = 0 ; j < n - c - 1; j++)
    {
      if (array[j] > array[j+1]) 
      {
        temp       = array[j];
        array[j]   = array[j+1];
        array[j+1] = temp;
      }
    }
  }
 
  printf("Sorted list in ascending order:\n");
 
  for ( int i=0 ; i < n ; i++ )
     printf("%d\n", array[i]);
 
  return 0;
}

C++ Code

#include <iostream>

using namespace std;
 
int main()
{
  int array[100], temp, n;
 
  cout <<"Enter number of elements\n";
  scin >> n;
 
  cout << "Enter %d integers\n";
 
  for (int i = 0; i < n; i++)
    cin >> array[i];
 
  for (int i = 0 ; i < ( n - 1 ); i++)
  {
    for (int j = 0 ; j < n - c - 1; j++)
    {
      if (array[j] > array[j+1]) 
      {
        temp       = array[j];
        array[j]   = array[j+1];
        array[j+1] = temp;
      }
    }
  }
 
  cout << "Sorted list in ascending order:\n";
 
  for ( int i=0 ; i < n ; i++ )
     cout << array[i];
 
  return 0;
}

 

Categories: C Language,C Programs,Computer Science

Tags: ,,

Leave A Reply

Your email address will not be published.

×