pw_

Sorting Algorithms

pw_
Nov 5th, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.95 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.Arrays;
  3.  
  4. public class Main {
  5.  
  6.     public static void main(String[] args) {
  7.         Random random = new Random();
  8.         int[]testArray = new int[10000];
  9.         for(int i = 0; i < testArray.length; i++) {
  10.             testArray[i] = random.nextInt(100);
  11.         }
  12.         int[]testArray2 = Arrays.copyOf(testArray, testArray.length);
  13.         int[]testArray3 = Arrays.copyOf(testArray, testArray.length);
  14.         int[]testArray4 = Arrays.copyOf(testArray, testArray.length);
  15.         int[]testArray5 = Arrays.copyOf(testArray, testArray.length);
  16.         int[]testArray6 = Arrays.copyOf(testArray, testArray.length);
  17.         int[]testArray7 = Arrays.copyOf(testArray, testArray.length);
  18.         //int[]testArray6 = {9,8,1,6,5,2};
  19.        
  20.         //BUBBLE SORT
  21.         System.out.println("BUBBLE SORT");
  22.         //Main.printArray(testArray);
  23.         long start = System.currentTimeMillis();
  24.         BubbleSort.sort(testArray);
  25.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start) + " milisekund");
  26.         //Main.printArray(testArray);
  27.         //SELECT SORT
  28.         System.out.println("\nSELECT SORT");
  29.         //Main.printArray(testArray2);
  30.         long start2 = System.currentTimeMillis();
  31.         SelectSort.sort(testArray2);
  32.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start2) + " milisekund");
  33.         //Main.printArray(testArray2);
  34.         //INSERTION SORT
  35.         System.out.println("\nINSERTION SORT");
  36.         //Main.printArray(testArray3);
  37.         long start3 = System.currentTimeMillis();
  38.         InsertionSort.sort(testArray3);
  39.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start3) + " milisekund");
  40.         //Main.printArray(testArray3);
  41.         //MERGE SORT
  42.         System.out.println("\nMERGE SORT");
  43.         //Main.printArray(testArray4);
  44.         long start4 = System.currentTimeMillis();
  45.         MergeSort.sort(testArray4);
  46.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start4) + " milisekund");
  47.         //Main.printArray(testArray4);
  48.         //HEAP SORT
  49.         System.out.println("\nHEAP SORT");
  50.         //Main.printArray(testArray5);
  51.         long start5 = System.currentTimeMillis();
  52.         HeapSort.sort(testArray5);
  53.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start5) + " milisekund");
  54.         //Main.printArray(testArray5);
  55.         //QUICK SORT
  56.         System.out.println("\nQUICK SORT");
  57.         //Main.printArray(testArray6);
  58.         long start6 = System.currentTimeMillis();
  59.         QuickSort.sort(testArray6);
  60.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start6) + " milisekund");
  61.         //Main.printArray(testArray6);
  62.         //SHELL SORT
  63.         System.out.println("\nSHELL SORT");
  64.         //Main.printArray(testArray7);
  65.         long start7 = System.currentTimeMillis();
  66.         //ShellSort.sort(testArray7, ShellSort::shellDistance);  
  67.         ShellSort.sort(testArray7, ShellSort::sedgewickDistance);  
  68.         System.out.println("Czas sortowania: " + (System.currentTimeMillis() - start7) + " milisekund");
  69.         //Main.printArray(testArray7);
  70.  
  71.     }
  72.     private static void printArray(int[]arr) {
  73.         for(int j = 0; j < arr.length; j++) {
  74.             System.out.print(arr[j] + " ");
  75.         }
  76.         System.out.println();
  77.     }
  78. }
  79.  
  80. public class SortUtils {
  81.  
  82.     public static void swap(int[]array, int index1, int index2) {
  83.         int temp = array[index1];
  84.         array[index1] = array[index2];
  85.         array[index2] = temp;
  86.     }
  87. }
  88.  
  89. public class InsertionSort {  //sortowanie przez wstawianie
  90.  
  91.     public static void sort(int[]arrayToSort) {
  92.         int n = arrayToSort.length;
  93.         int current;
  94.         int otherIndex;
  95.         for(int i = 1; i < n; i++) {   //zaczynamy od drugiego elementu
  96.             current = arrayToSort[i];  //zapamietujemy 2gi element tablicy
  97.             otherIndex = i;            //j.w
  98.             while(otherIndex > 0 && current < arrayToSort[otherIndex - 1]) {  //sprawdzamy czy obecny element jest mniejeszy od poprzedniego
  99.                 arrayToSort[otherIndex] = arrayToSort[otherIndex - 1];  //podmieniamy pomocniczą zmienną, liczbą 1sza (teraz na pozycji 0 i 1 jest ta sama liczba, większa)
  100.                 otherIndex--;  //zmniejszamy indeks na poprzedni (przesuwamy sie po tablicy do tyłu) i porównujemy wartosci liczb ponownie.
  101.             }
  102.             arrayToSort[otherIndex] = current;  //ustawiamy naszą zapamiętaną liczbę na odpowiedniej pozycji w tablicy do posortowania (pozycja ta będzie wiadoma dzięki petli "while")
  103.         }
  104.     }
  105. }
  106.  
  107. public class SelectSort {   //sortowanie przez wybieranie najmniejszego indeksu
  108.  
  109.     public static void sort(int[]arrayToSort) {
  110.         int n = arrayToSort.length;
  111.         int minIndex;
  112.         for(int i = 0; i < n - 1; i++) {
  113.             minIndex = i;   //ustawianie wartosci indeksu "i" ktorego bedziemy porównywać z reszta liczb
  114.             for(int j = i + 1; j < n; j++) {
  115.                 if(arrayToSort[j] < arrayToSort[minIndex]) {  //jeżeli następna liczba jest mniejsza niz wartosc indeksu to ustawiamy nowy indeks
  116.                     minIndex = j;  //ustawiamy nowe indeks
  117.                 }
  118.             }
  119.                 if(minIndex != i){                    //sprawdzanie czy zmieniliśmy wartość pierwotnego indeksu.
  120.                     SortUtils.swap(arrayToSort, minIndex, i); //zamiana miejscami mniejszej liczby spod "i" z minIndeks
  121.             }
  122.         }
  123.     }
  124. }
  125.  
  126. public class BubbleSort {  //sortowanie babelkowe. Największa liczba ustawiana jest na samym koncu
  127.  
  128.     public static void sort(int[]arrayToSort) {
  129.         int n = arrayToSort.length;
  130.         int it = 0;  // licznik konca tablicy (w petli for nie bedzie już porownywal ostatnich znaków)
  131.         boolean swapped = true;
  132.         while (it < n - 1 && swapped) {
  133.             swapped = false;
  134.             for (int j = 0; j < n - 1 - it; j++) {  //iterujemy po ciagu liczb z pominięciem "it"
  135.                 if (arrayToSort[j] > arrayToSort[j + 1]) {  //porównujemy dwie liczby
  136.                     SortUtils.swap(arrayToSort, j, j + 1);  //jak liczba po lewej stronie jest większa to zamieniamy ją miejscami z liczba po prawej stronie
  137.                     swapped = true;  //warunek ktory sprawdza czy byla jakas zamiana.
  138.                 }
  139.             }
  140.             it++; //zmniejszamy tablice
  141.         }
  142.     }
  143. }
  144.  
  145. public class MergeSort {   //sortowanie przez scalanie
  146.  
  147.     private static int[]extraArray;
  148.  
  149.     public static void sort(int[]arrayToSort) {
  150.         extraArray = new int[arrayToSort.length];
  151.         mergeSort(arrayToSort, 0 , arrayToSort.length -1); //lewa granica i prawa granica tablicy
  152.     }
  153.     private static void mergeSort (int[]array, int leftIndex, int rightIndex) {
  154.         if (leftIndex < rightIndex) {  //dzielenie tablicy do jednego elementu
  155.             int middle = (leftIndex + rightIndex) / 2;
  156.             mergeSort(array, leftIndex, middle);  //dzielenie lewej czesci do 2 elementów rekurencyjnie
  157.             mergeSort(array, middle + 1, rightIndex);  //dzielenie prawej czesci do 2 elementów rekurencyjnie
  158.             merge(array, leftIndex, middle, rightIndex); //łaczenie czesci lewej i prawej (wykona sie dopiero wtedy gdy wywołania rekurencyjne beda skonczone)
  159.         }
  160.     }
  161.     private static void merge(int[]array, int leftIndex, int middleIndex, int rightIndex) {  //wypisywanie 0ego i 1ego elementu tablicy do posortowania (plus zwiekszenie licznika "i")
  162.         for (int i = leftIndex; i <= rightIndex; i++) {
  163.             extraArray[i] = array[i];   //do tablicy pomocniczej wpisujemy dwie kolejne liczby (z tablicy do posortowania)
  164.         }
  165.  
  166.         //ustawianie wskaźników
  167.         int finger1 = leftIndex;   //pierwsza liczba z lewej strony o indeksie 0   --lewa
  168.         int finger2 = middleIndex + 1; //pierwsza liczba z prawej strony           --prawa
  169.         int current = leftIndex;
  170.         ///////////////////////
  171.  
  172.         while(finger1 <= middleIndex && finger2 <= rightIndex) {  //?????
  173.             //porownywanie elementów
  174.             if(extraArray[finger1] <= extraArray[finger2]) {  //porownywanie wartosci liczb po indeksie (czy wartosc finger 1 jest mniejsza o wartosci finger2)
  175.                 array[current] = extraArray[finger1];
  176.                 finger1++;
  177.             }
  178.             else {
  179.                 array[current] = extraArray[finger2];
  180.                 finger2++;
  181.             }
  182.             ////////////////////////////
  183.             current++;  //zwiekszam indeks o jeden i wpisuje/porównuje kolejną liczbę
  184.         }
  185.         while(finger1 <= middleIndex) {   //jezeli prawa strona sie skonczyla i jest posortowana to tutaj zostaje dopisana liczba z lewej storny lub jak
  186.                                           //z lewej strony sie skonczy liczba to to sie nie wykona bo prawa strona bewdzie juz na swoim miejscu.
  187.             array[current] = extraArray[finger1];
  188.             finger1++;
  189.             current++;
  190.         }
  191.     }
  192. }
  193.  
  194. public class HeapSort {  //sortowanie przez kopcowanie
  195.  
  196.     public static void sort(int[]arrayToSort) {
  197.         int n = arrayToSort.length;
  198.        
  199.         for (int i = n/2 - 1; i>=0; i--){      //tworzenie kopca i szukanie ostatniego rodzica
  200.             HeapSort.validateMaxHeap(arrayToSort, n, i);    //sprawdzanie czy jest 'maxheap'
  201.         }
  202.         for (int i = n - 1; i>0; i--){          //iterowanie od konca do poczatku
  203.             SortUtils.swap(arrayToSort, 0, i);  //zamiana ostatniego elementu kopca z pierwszysm rodzicem (czyli najwieksza wartosc wedruje na sam koniec)
  204.             n--;                                //zmniejszanie kopca poprzez odcięcię ostatniego dziecka z najwiekszą wartością
  205.             HeapSort.validateMaxHeap(arrayToSort, n, 0); //walidacja kopca zmniejszonego o 1
  206.         }
  207.     }
  208.     private static void validateMaxHeap(int[] array, int heapSize, int parentIndex){  
  209.        
  210.         ///////ustawianie wskaźników
  211.         int maxIndex = parentIndex;
  212.         int leftChild = parentIndex * 2 + 1;
  213.         int rightChild = parentIndex * 2 + 2;
  214.         ////////////////////////////
  215.        
  216.         if(leftChild < heapSize && array[leftChild] > array[maxIndex]){  //sprawdzanie po wartosci
  217.             maxIndex = leftChild;
  218.         }
  219.         if(rightChild < heapSize && array[rightChild] > array[maxIndex]){ //sprawdzanie po wartosci
  220.             maxIndex = rightChild;
  221.         }
  222.         if(maxIndex != parentIndex){                       //jeżeli rodzic został zamieniony z dzieckiem to:
  223.             SortUtils.swap(array, maxIndex, parentIndex);  //zamieniamy miejscami parentIndex z maxIndex (od tej pory oryginalny rodzic jest na mijescu dziecka ktore było większe)
  224.             validateMaxHeap(array, heapSize, maxIndex);    //i sprawdzamy rekurencyjnie czy struktura drzewa jest zachowana. (czy rodzic ma większą wartość niz jego dzieci)
  225.         }
  226.     }
  227. }
  228.  
  229. public class QuickSort {   //Sorotwanie z pivotem
  230.  
  231.     public static void sort(int[]arrayToSort) {
  232.         int n = arrayToSort.length;
  233.         quicksort(arrayToSort, 0, n-1);
  234.     }
  235.     public static void quicksort(int[]array, int left, int right) {
  236.         if (left >= right){  //sprawdzanie czy jest wiecej niz jedna liczba
  237.             return;
  238.         }
  239.         ///////////////////////////ustawianie wskaźników
  240.         int pivotValue = array[right];
  241.         int border = left - 1;   //granica po ktorej sortujemy
  242.         int i = left;            //iteracja po liczbach
  243.         ///////////////////////////
  244.  
  245.  
  246.         while (i < right){                //jak doszlismy do konca lanucha to wychodzimy z petli...
  247.             if (array[i] < pivotValue){   //sprawdzanie wartości (czy liczba po lewej stronie granicy jest mniejsza od pivota)
  248.                 border++;                 //jak jest mniejsza to przesywamy granice o jeden w prawo
  249.                 if(border != i){          //zamieniamy liczbe spod "i" z liczba po lewej stronie od granicy
  250.                     SortUtils.swap(array, border, i);
  251.                 }
  252.             }
  253.             i++;
  254.         }
  255.         border++;   //...i przesuwamy granice w prawo
  256.         if (border != right){  //zamieniamy miejscami pivota z liczba po lewej stronie od granicy
  257.             SortUtils.swap(array, border, right);
  258.         }
  259.         quicksort(array, left, border-1);  //sprawdzamy lewa strone rekurencyjnie
  260.         quicksort(array, border+1, right);  //sprawdzamy prawa strone rekurencyjnie
  261.     }
  262.  
  263. }
  264.  
  265. import java.util.ArrayList;
  266. import java.util.Collections;
  267. import java.util.function.Function;  
  268.  
  269. public class ShellSort {
  270.    
  271.     public static void sort(int[]arr, Function<Integer, Integer[]> distGenerator){  //interfejs java8 - poczytac
  272.         int n = arr.length;
  273.         int iter = 1;
  274.         Integer[] distances = distGenerator.apply(n);
  275.         int distance = distances[distances.length - iter];  //pobieranie dystansu od konca (od najwiekszego dystansu do najmniejszego)
  276.         int current, otherIndex;  //zmienne dla porównywanych liczb
  277.         while(distance >= 1){  //SPRAWDZIĆ
  278.             for(int i = distance; i < n; i++){  //sortowanie przez wstawianie
  279.                 current = arr[i];  //wartosc "i"
  280.                 otherIndex = i;  //indeks "i"
  281.                 while(otherIndex >= distance && current < arr[otherIndex - distance]){ //porównujemy wartość pierwszej liczby zza połowy z wartością liczby minus dystans (czyli prawą liczbe z lewą ze swojej pary)
  282.                     arr[otherIndex] = arr[otherIndex - distance];  //jeżeli liczba po prawej stronie jest mniejsza to nadpisujemy ją liczbą z lewej strony.
  283.                     otherIndex -= distance;  //ustawiamy indeks na liczbie po lewej stronie zeby ją zmienić. (ustawiamy ja tak że odejmujemy wartosc dystnasu)
  284.                 }
  285.                 arr[otherIndex] = current;  //ustawiamy zamieniona liczbe w nowe miejsce (czyli zapamiętana z prawej strony (current) na lewą stronę. (czyli minus dystans).
  286.             }
  287.             distance = distances[distances.length - ++iter];  //zmniejszamy dystans przez pobranie z wygenerowanej wczesniej tablicy dystansów, kolejnego dystansu.
  288.         }
  289.     }
  290.    
  291.     public static Integer[] shellDistance(int numberOfElements){
  292.         ArrayList<Integer> distances = new ArrayList<>();
  293.         int iteration = 1;
  294.         int generated;
  295.         do{
  296.             generated = numberOfElements / (int)Math.pow(2, iteration);
  297.             distances.add(generated);
  298.             iteration++;
  299.         }while(generated > 0);
  300.         Collections.reverse(distances);
  301.         return distances.toArray(new Integer[distances.size()]);
  302.     }
  303.    
  304.     // 4^k + 3*2^(k-1) + 1
  305.     public static Integer[] sedgewickDistance(int numberOfElements){
  306.         int generated = 0;
  307.         ArrayList<Integer> distances = new ArrayList<>();
  308.         int k = 0;
  309.         while(generated < numberOfElements){
  310.             if(distances.isEmpty()){
  311.                 distances.add(0);
  312.                 distances.add(1);
  313.             } else{
  314.                 generated = (int) (Math.pow(4, k) + 3 * Math.pow(2, k-1) + 1);
  315.                 if(generated < numberOfElements){
  316.                     distances.add(generated);
  317.                 }
  318.             }
  319.             k++;
  320.         }
  321.         return distances.toArray(new Integer[distances.size()]);
  322.     }
  323.    
  324. }
Advertisement
Add Comment
Please, Sign In to add comment