hiro
0
Q:

selection sort java

public static void SelectionSort(int[] arr)
{
  int small;
  for (int i = 0; i <arr.length - 1; i++)
  {
    small = i;
    for (int j = i + 1; j < arr.length; j++)
    {
      //if current position is less than previous smallest
      if (arr[j] < arr[small])
      {
        small = j;
        
        //swap values
        int temp = arr[i];
        arr[i] = arr[small];
        arr[small] = temp; 
      }
  	}
  }
}
5
static void selectionSort(int[] arr) {
        int lowest, lowestIndex;
        for(int i = 0; i < arr.length -1; i++) {
            //Find the lowest
            lowest = arr[i];
            lowestIndex = i;
            for(int j = i; j < arr.length; j++) {
                if(arr[j] < lowest) {
                    lowest = arr[j];
                    lowestIndex = j;
                }
            }
            //Swap
            if(i != lowestIndex) {
                int temp = arr[i];
                arr[i] = arr[lowestIndex];
                arr[lowestIndex] = temp;
            }
            
        }
    }
0
// Por ter uma complexidade alta,
// não é recomendado para um conjunto de dados muito grande.
// Complexidade: O(n²) / O(n**2) / O(n^2)
// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html

function selectionSort(vetor) {
    let minor;
    for (let i = 0; i < vetor.length - 1; i += 1) {
        minor = i;
        for (let j = i + 1; j < vetor.length; j += 1) {
            if (vetor[j] < vetor[minor]) {
                minor = j;
            }
        }
        if (i !== minor) {
            [vetor[i], vetor[minor]] = [vetor[minor], vetor[i]];
        }
    }
    return vetor;
}

selectionSort([1, 2, 5, 8, 3, 4]);
3

New to Communities?

Join the community