selection sort implementation java code example

Example 1: Selection sort java

// example on selection sort java
public class SelectionSortInJava
{
   void toSort(int[] arrNum)
   {
      int number = arrNum.length;
      for(int a = 0; a < number - 1; a++)
      {
         // finding minimum element
         int minimum = a;
         for(int b = a + 1; b < number; b++)
         {
            if(arrNum[b] < arrNum[minimum])
            {
               minimum = b;
            }
         }
         // swapping minimum element with first element
         int temp = arrNum[minimum];
         arrNum[minimum] = arrNum[a];
         arrNum[a] = temp;
      }
   }
   // printing array
   void displayArray(int[] arrPrint)
   {
      int num = arrPrint.length;
      for(int a = 0; a < num; ++a)
      {
         System.out.print(arrPrint[a] + " ");
      }
      System.out.println();
   }
   public static void main(String[] args)
   {
      SelectionSortInJava obj = new SelectionSortInJava();
      int[] arrInput = {5, 4, -3, 2, -1};
      obj.toSort(arrInput);
      System.out.println("After sorting : ");
      obj.displayArray(arrInput);
   }
}

Example 2: selection sort in 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; 
      }
  	}
  }
}

Example 3: selection sort java

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;
            }
            
        }
    }

Tags:

Java Example