-2

How to change the following sorting algorithm to operate on a single array arr[]? For now, I have to transfer elements from one array arr[] to res[]. How to preform all operations on arr[]? Here is my code:

void main(){
    
    int arr [] = {1, 14, 5, 18, 3, 1};
    int res [] = {0, 0, 0, 0, 0, 0};
    
    int x = 0;
    int y = 0;
    
    for(int i = 0; i < 6; i++) {
              x = 0;
          
        for(int k = 0; k < 6; k++){
                       
            if(arr[k] > x){
            x = arr[k];
            y = k;
            }
         }    
      arr[y] = 0;
      res[5 - i] = x;
    
    }
   
     for (int z = 0; z < 6; z++){
       printf("%d ", res[z]);
    }
 }
Some programmer dude
  • 363,249
  • 31
  • 351
  • 550

1 Answers1

1

Just swap the elements in array that mistakenly positioned thoroughly by checking one by one. This called as bubble sort. There's also another sorting algorithms u can search online or check visualgo for animated process for understanding.

void main(){
    
    int arr [] = {1, 14, 5, 18, 3, 1};    
    
    // This applies bubble sort
    for(int i = 0; i < 6; i++) {
        for(int k = 0; k < 6; k++){
            // Swap elements in an array  
            if(arr[i] > arr[k]){
                int x = arr[k];
                arr[k] = arr[i];
                arr[i] = x;
            }
         }        
    }
   
     for (int z = 0; z < 6; z++){
       printf("%d ", res[z]);
    }
 }
Dhana D.
  • 173
  • 12