Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. public class Sorting {
  2.     public static void main(String[] args) {
  3.  
  4.         int[] array = {2,6,99,432,121,463424,23,3,4,6,3,34,25,4,3,2,1};
  5.  
  6.         insertionsort(array);
  7.  
  8.         for(int i = 0; i<array.length; i++) System.out.println(array[i]);
  9.        
  10.        
  11.     }
  12.  
  13.  
  14.     public static void bubblesort(int[] array) {
  15.  
  16.         boolean swapped;
  17.  
  18.         for(int i = 0; i < array.length; i++) {
  19.  
  20.             swapped = false; //set swapped to false because nothing has been swapped
  21.             for(int j = 0; j < array.length - 1 - i; j++) { //-1 because we need to access j+1
  22.                 if (array[j] > array[j+1]) {
  23.                     //swap
  24.                     int temp = array[j];
  25.                     array[j] = array[j+1];
  26.                     array[j+1] = temp;
  27.                     swapped = true;
  28.                 }
  29.             }
  30.  
  31.             if (swapped == false) break; //if no swaps were made that means the list is sorted
  32.         }
  33.     }
  34.  
  35.  
  36.     public static void selectionsort(int[] array) {
  37.  
  38.         for(int i = 0; i < array.length; i++) {
  39.             //to move boundary n times
  40.             int min_index = i;
  41.             for(int j = i+1; j < array.length; j++) {
  42.                 if (array[j] < array[min_index]) min_index = j; //find min index in i+1 to n
  43.             } //after this for loop we should have the index of min value in i to n (i if it was not updated)
  44.             if (min_index != i) { //don't do anything if min_index was i (it's in the right position)
  45.                 //swap array[min_index] and array[i]
  46.                 int temp = array[min_index];
  47.                 array[min_index] = array[i];
  48.                 array[i] = temp;
  49.             }
  50.         }
  51.     }
  52.  
  53.     public static void insertionsort(int[] array) {
  54.  
  55.         for(int i = 0; i < array.length; i++) {
  56.             int k = i; //store current i in k to so we can change k without breaking the loop
  57.             int elem = array[i];
  58.             while(k>0 && elem < array[k-1]) {
  59.                 array[k] = array[k-1];
  60.                 k--;
  61.             }
  62.             array[k] = elem;
  63.         }
  64.  
  65.     }
  66.  
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement