Bubble sort (Ascending order) for n number of integers using Dynamic memory allocation.
- Ben
- Feb 25, 2018
- 1 min read
#include <iostream>
using namespace std;
void swap(int *a, int *b) { int temp; temp = *a; *a=*b; *b = temp; }
void bubblesort(int* arr, int n) { for (int i=0;i < n-1; i++) { for(int j=0; j<n-i-1; j++) { if(arr[j]>arr[j+1]) { swap(&arr[j], &arr[j+1]); // Swap done for getting ascending order } } } }
int main() { // Get the size of array int a; cout<<"Enter the size of array "<<endl; cin>>a; // Dynamically allocate memory int *arr= new int(a); // Get input array cout<<"Enter the array elements"<<endl; for(int i=0; i<a; i++) { cin>>arr[i]; } // Do bubblesort bubblesort(arr, a); // Display sorted array for(int i=0; i<a; i++) { cout<<arr[i]<<" "; } // free memory delete[] arr; return 0; }
Comments