Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //wrong algo
- void sort (int arr[], int n)
- {
- for (int i=0; i<n-1 ; i++)
- {
- for (int j=i+1; j<n; j++)
- {
- if (arr[i]>arr[j])
- {
- swap(&arr[i], &arr[j]);
- }
- }
- }
- }
- //right algo
- for (i=0; i<n; i++) // at MAXIMUM, we need to run n times to fully sort the array
- {
- flag=0;
- for (j=0; j<n-1; j++) //as the unsorted array consists of n elements, the inner loop should run (n-1) times.
- {
- if (unsorted[j]>unsorted[j+1])
- {
- // the process of swapping two elements if the first element is greater than the later element
- temp = unsorted[j];
- unsorted[j]=unsorted[j+1];
- unsorted[j+1]=temp;
- flag=1;
- }
- }
- if (flag==0)
- {
- break; //this is for optimization, we donot need to run the sort n times always as the biggest numbers automatically bubbles up at the right
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement