repl.it
@Apass_Jack/

CachingInsertionSort_cs111111

Java

No description

fork
loading
Files
  • Main.java
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.Arrays;

// repl.it requires the class name be Main.
public class Main {
  static class Node {
    int key;
    Node prev;
    Node next;

    Node(int key) {
      this.key = key;
    }
  }

  static void cachingSort(int[] array) {
    int last_key = array[0];
    Node head = new Node(last_key);
    Node tail = head;
    Node last = head;

    for (int i = 1; i < array.length; i++) {
      int current_key = array[i];
      if (last_key > current_key) {
        Node tmp = last.prev;

        while (tmp != null && tmp.key > current_key) {
          tmp = tmp.prev;
        }

        if (tmp == null) {
          Node newNode = new Node(current_key);
          newNode.prev = null;
          newNode.next = head;
          head.prev = newNode;
          head = newNode;
          last = newNode;
        } else {
          Node newNode = new Node(current_key);
          newNode.prev = tmp;
          newNode.next = tmp.next;
          tmp.next = newNode;
          newNode.next.prev = newNode;
          last = newNode;
        }

      } else {
        Node tmp = last.next;
        while (tmp != null && tmp.key <= current_key) {
          tmp = tmp.next;
        }

        if (tmp == null) {
          Node newNode = new Node(current_key);
          newNode.prev = tail;
          newNode.next = null;
          tail.next = newNode;
          tail = newNode;
          last = newNode;
        } else {
          Node newNode = new Node(current_key);
          newNode.prev = tmp.prev;
          newNode.next = tmp;
          newNode.prev.next = newNode;
          tmp.prev = newNode;
          last = newNode;
        }
      }

      last_key = last.key;
    }

    int index = 0;
    for (Node node = head; node != null; node = node.next) {
      int key = node.key;
      array[index++] = key;
    }
  }

  public static void main(String[] args) {
    int[] a = { 0, 9, 6, 9, 9, 2, 8, 7, 4, 4 };
    cachingSort(a);
    System.out.println(Arrays.toString(a));
    for (int i = 1; i < a.length; i++) {
      if (a[i - 1] > a[i]) {
        throw new IllegalStateException("Not ordered!");
      }
    }
  }
}