selection sort example

Example 1: selection sort

#include <bits/stdc++.h>

using namespace std; 

void selectionSort(int arr[], int n){
    int i,j,min;
    
    for(i=0;i<n-1;i++){
        min = i;
        for(j=i+1;j<n;j++){
            if(arr[j] < arr[min]){
                min = j;
            }
        }
        if(min != i){
            swap(arr[i],arr[min]);
        }
    }
}

int main()  
{  
    int arr[] = { 1,4,2,5,333,3,5,7777,4,4,3,22,1,4,3,666,4,6,8,999,4,3,5,32 };  
    int n = sizeof(arr) / sizeof(arr[0]);  

    selectionSort(arr, n);  

    for(int i = 0; i < n; i++){
        cout << arr[i] << " ";
    }

    return 0;  
}

Example 2: selection sort

def ssort(lst):
    for i in range(len(lst)):
        for j in range(i+1,len(lst)):
            if lst[i]>lst[j]:lst[j],lst[i]=lst[i],lst[j]
    return lst
if __name__=='__main__':
    lst=[int(i) for i in input('Enter the Numbers: ').split()]
    print(ssort(lst))

Example 3: selection sort

procedure selection sort 
   list  : array of items
   n     : size of list

   for i = 1 to n - 1
   /* set current element as minimum*/
      min = i    
  
      /* check the element to be minimum */

      for j = i+1 to n 
         if list[j] < list[min] then
            min = j;
         end if
      end for

      /* swap the minimum element with the current element*/
      if indexMin != i  then
         swap list[min] and list[i]
      end if
   end for
	
end procedure

Example 4: selection sort

void sort(int *arr, int n){
        
        // Incrementa di 1 il limite inferiore del sub array da ordinare
        for (int i = 0; i < n-1; i++) 
        { 
            // Trova il minimo nel subarray da ordinare
            int indice_min = i; 
            for (int j = i+1; j < n; j++) {
                
                // Confronto per trovare un nuovo minimo
                if (arr[j] < arr[indice_min]) 
                    indice_min = j; // Salvo l'indice del nuovo minimo
            }
            
            // Scambia il minimo trovato con il primo elemento
            swap(arr,indice_min,i);    
        } 
    }
    
     void swap(int *arr, int a , int b){
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
    
}

Tags:

C Example