 # Untitled

Dec 2nd, 2022
699
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. //wrong algo
2. void sort (int arr[], int n)
3. {
4.     for (int i=0; i<n-1 ; i++)
5.     {
6.         for (int j=i+1; j<n; j++)
7.         {
8.             if (arr[i]>arr[j])
9.             {
10.                 swap(&arr[i], &arr[j]);
11.             }
12.         }
13.     }
14. }
15.
16.
17.
18.
19. //right algo
20.  for (i=0; i<n; i++) // at MAXIMUM, we need to run n times to fully sort the array
21.     {
22.         flag=0;
23.         for (j=0; j<n-1; j++) //as the unsorted array consists of n elements, the inner loop should run (n-1) times.
24.         {
25.             if (unsorted[j]>unsorted[j+1])
26.             {
27.                 // the process of swapping two elements if the first element is greater than the later element
28.                 temp = unsorted[j];
29.                 unsorted[j]=unsorted[j+1];
30.                 unsorted[j+1]=temp;
31.                 flag=1;
32.             }
33.         }
34.
35.         if (flag==0)
36.         {
37.             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
38.         }
39.
40.     }
41.