Guest User

Untitled

a guest
Apr 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. // Insertion sort
  2.  
  3.  
  4. public class insertionSort
  5. {
  6. public static void main(String[] args) {
  7. int [] numbers = new int[]{2,5,7,23,12,1,79,4};
  8.  
  9. List<Integer> result1 = insertionSort_1(numbers);
  10.  
  11. System.out.println("original array:");
  12. for (int num : numbers) System.out.print(num + " ");
  13. System.out.println("\n" +"sorted array with List implementation:");
  14. for (Integer num : result1) System.out.print(num + " ");
  15.  
  16. int [] result2 = insertionSort_2(numbers);
  17.  
  18. System.out.println("\n" +"sorted array with classic arrays sorting:");
  19. for (Integer num : result2) System.out.print(num + " ");
  20.  
  21. }
  22.  
  23. //Using List implementation
  24. public static List<Integer> insertionSort_1(int[] arr) {
  25.  
  26. List<Integer> sorted = new ArrayList<>();
  27.  
  28. outer: for (int num : arr) {
  29. for (int i = 0; i < sorted.size(); i++) {
  30. if (num < sorted.get(i)) {
  31. sorted.add(i, num);
  32. continue outer;
  33. }
  34. }
  35. sorted.add(sorted.size(), num);
  36. }
  37.  
  38. return sorted;
  39. }
  40.  
  41. //classic array sorting
  42. public static int [] insertionSort_2(int [] arr) {
  43. int [] sorted = new int[arr.length];
  44.  
  45. for (int i = 0; i < sorted.length; i++) {
  46. sorted[i] = arr[i];
  47. }
  48.  
  49. int temp, j; //in temp we put our "the first" element of unsorted part, j is the number of cell, in which we put this element after sorting
  50.  
  51. for (int i = 0; i < sorted.length - 1; i++) {
  52.  
  53. if (sorted[i] > sorted[i + 1]) {
  54.  
  55. temp = sorted[i + 1];
  56. sorted[i + 1] = sorted[i];
  57. j = i;
  58.  
  59. while (j > 0 && temp < sorted[j - 1]) {
  60. sorted[j] = sorted[j - 1];
  61. j--;
  62. }
  63. sorted[j] = temp;
  64. }
  65.  
  66. }
  67. return sorted;
  68. }
  69.  
  70. }
Add Comment
Please, Sign In to add comment