Skip to content

Instantly share code, notes, and snippets.

@Rabishranjan08
Created September 15, 2021 07:55
Show Gist options
  • Select an option

  • Save Rabishranjan08/849657ac84acc64c3a9a9005aee15773 to your computer and use it in GitHub Desktop.

Select an option

Save Rabishranjan08/849657ac84acc64c3a9a9005aee15773 to your computer and use it in GitHub Desktop.
Algorithm to sort an array
#include<bits/stdc++.h>
using namespace std;
/*1.We are given with an input array which is supposed to be sorted in ascending order
2.We start with the first element and i=0 index and check if the element present at i+1 is greater then we swap the elements at index i and i+1.
3.If above is not the case, then no swapping will take place.
4.Now “ i ” gets incremented and the above 2 steps happen again until the array is exhausted.
5.We will ignore the last index as it is already sorted.
6.Now the largest element will be at the last index of the array.
7.Now we will again set i=0 and continue with the same steps that will eventually place second largest at second last place in the array. Now the last 2 indexes of the array are sorted.
*/
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void sorting(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]);
}
}
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
sorting(arr,n);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment