hikipedia

Sorts.java

Nov 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. package project;
  2.  
  3. import java.util.*;
  4.  
  5. public class Sorts {
  6.     public static void main(String[] args){
  7.         int[] arr = {2, 9, 8,6, 7, 1, 3, 5, 4, 10};
  8.         bubbleSort(arr);
  9.         //selectionSort(arr);
  10.         System.out.println(Arrays.toString(arr));
  11.     }
  12.     public static int[] bubbleSort(int[] arr){
  13.         int counter = 0;
  14.         boolean swapped = false;
  15.         do {
  16.             swapped = false;
  17.             for (int i = 0; i < arr.length - 1; i++) {
  18.                 if (arr[i] > arr[i+1]){
  19.                     int temp = arr[i];
  20.                     arr[i] = arr[i + 1];
  21.                     arr[i + 1] = temp;
  22.                     swapped = true;
  23.                 }
  24.                 counter++;
  25.             }
  26.         } while(swapped == true);
  27.         System.out.println(counter);
  28.         return arr;
  29.     }
  30.     public static int[] selectionSort(int[] arr){
  31.         int counter = 0;
  32.         for (int i = 0; i < arr.length - 1; i++){
  33.             for (int j = 0 ; j < arr.length - 1; j++){
  34.                 if (arr[j] > arr[j+1]){
  35.                     int temp = arr[j];
  36.                     arr[j] = arr[j + 1];
  37.                     arr[j + 1] = temp;
  38.                 }
  39.                 counter++;
  40.             }
  41.         }
  42.         System.out.println(counter);
  43.         return arr;
  44.     }
  45. }
Add Comment
Please, Sign In to add comment