Skip to content

Instantly share code, notes, and snippets.

@fpdjsns
Last active December 17, 2021 05:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fpdjsns/bcd325e4757bcf16c35768145eb7cf5a to your computer and use it in GitHub Desktop.
Save fpdjsns/bcd325e4757bcf16c35768145eb7cf5a to your computer and use it in GitHub Desktop.
Bubble_Sort. [Input : The first line contains an integer, n, denoting the number of an array size. next line contains n space-separated integers the array data.(like 4 5 3 6 7 2 1)] [output: Print n space-separated integers the sorted array data.]
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//swap
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
//print array
void Print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
//bubble sort
void Bubble_Sort(int arr[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j] > arr[j + 1])//ascending (if, descending change '>' to '<')
swap(arr[j], arr[j + 1]);
}
cout << i + 1 << " : ";
Print(arr, n);
}
}
int main()
{
int n; //array size
int *arr; //unsorted array
cin >> n;
arr = new int[n];
for (int i = 0; i < n; i++)
cin >> arr[i];
Bubble_Sort(arr, n); //bubble sort
cout << "sorted array : ";
Print(arr, n); //print sorted array
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment