Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Lab 12

import java.util.Arrays;
public class moddedSort
{
  public static void selectionSort(String[] array)
  {
    System.out.println("Unsorted selectionSort: " + Arrays.toString(array));
    for(int i = 0; i <= array.length - 1; i++)
    {
      int max = i;
      for(int j = i + 1; j < array.length; j++)
      {
        if(array[j].compareTo(array[max]) > 0)
        {
          max = j;
        }
      }
      String temp = array[i];
      array[i] = array[max];
      array[max] = temp;
    }
    System.out.println("Sorted selectionSort: " + Arrays.toString(array));  
  }
  
  public static void insertionSort(String [] array)
  {
    System.out.println("Unsorted insertionSort: " + Arrays.toString(array));
    
    String k;
    int i = 0;
    
    for(int j = 1; j <array.length; j++)
    {
        k = array[j];
        i = j - 1;
        
        while(i >= 0)
        {
           if(k.compareTo(array[i]) > 0)
           {
               break;
           }
           array[i + 1] = array[i];
           i--;
        }
        array[i + 1] = k;
    }

    System.out.println("Sorted insertionSort: " + Arrays.toString(array));
  }

  public static void dualSelectSort(int [] array)
  {
      System.out.println("Unsorted dualSelectSort: " + Arrays.toString(array));
    for (int i = 0; i < array.length / 2; i++)
    {
        int min = i;
        int max = array.length - 1 - i;  
        
        for (int j = i; j < array.length - i; j++) 
        {   
            if (array[j] < array[min]) 
            {                
            min = j;          
            }
                if (array[j] > array[max]) 
                {   
                max = j;           
                }      
        }
        if (max == i)
        {
        max = min;
        }

    }
  }
  public static void main(String [] args)
  {
    String [] a = {"a","q","b","z","f"};
    String [] b = {"r","w","i","x","j","e"};
    int [] c = {25, 3, 76, 7, 43, 82, 56, 97};

    selectionSort(a);
    System.out.println();
    
    insertionSort(b);
    System.out.println();
    
    dualSelectSort(c);
  }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.