select sort code 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

// C algorithm for SelectionSort

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

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

SelectionSort(List) {
  for(i from 0 to List.Length) {
    SmallestElement = List[i]
    for(j from i to List.Length) {
      if(SmallestElement > List[j]) {
        SmallestElement = List[j]
      }
    }
    Swap(List[i], SmallestElement)
  }
}

Example 5: 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