Friday, 10 February 2017

how to sort an array using bubble sort in c++?

#include<iostream>
#include<string>

using namespace
std;
int main()
{
 int arr[5];
 for (int i = 0; i < 5; ++i) {
  cout << "Enter the " << i + 1 << "number : " << endl;
  cin >> arr[i];
 }
 cout << "The unsorted array is " << endl;
 for (int i = 0; i < 5; ++i) {
  cout << arr[i] << " ," ;
 }
 cout << endl;
 // bubble sort ...
 int temp = 0;
 for (int i = 0; i < 5; ++i) {
  for (int j = 0; j < 4; ++j) {
   if (arr[j] > arr[j + 1]) {
    temp = arr[j + 1];
    arr[j + 1] = arr[j];
    arr[j] = temp;
   }
  }
 }
 cout << "The sorted array is " << endl;
 for (int i = 0; i < 5; ++i) {
  cout << arr[i] << " ,";
 }
 cout << endl;
 system("pause");
 return 0;
}

No comments:

Post a Comment