Implement Bubble sort algorithm in C++
Code
#include <iostream>using namespace std;int main(){int n, i, j, temp;int arr[50];cout << "Enter the size of array: ";cin >> n;cout << "Enter the elements of array: " << endl;for (i = 0; i < n; i++){cin >> arr[i];}for (i = 0; i < n; i++){for (j = 0; j < n - i - 1; j++){if (arr[j] > arr[j + 1]){temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}cout << "Sorted array: ";for (i = 0; i < n; i++){cout << arr[i] << " ";}cout << endl;return 0;}
Output
Enter the size of array: 5
Enter the elements of array:
4
2
7
4
1
Sorted array: 1 2 4 4 7
0 Comments
Post a Comment