Arrayss work well for unordered sequences, and even for ordered squences if they don't change much. But if you want to maintain an ordered list that allows quick insertions and deletions, you should use a linked data structure. so inserting an element using array may have to move a lot of data. if n = 1000 and x is less than all of those elements, then the method will move all 1000 elements. On average, inserting into a sorted array of n elements will move n/2 elements. So this is a F(n) operation. Deleting an element is simply the reverse of the insertion process, It too will have to move n/2 elements, on average, so deletion is also a f(n) operation.
The following is a simple example about linked list.
package com.albertshao.ds.array; public class TestNode { public static void main(String[] args) { Node start = new Node(22); Node p = start; for (int i = 1; i < 5; i++) p = p.next = new Node(22 + 11 * i); for (p = start; p != null; p = p.next) System.out.println(p.data); for (p = start; p != null; p = p.next) System.out.println(p); } } class Node { int data; Node next; Node(int data) { this.data = data; } }
The output is as follows:
22 33 44 55 66 com.albertshao.ds.array.Node@c17164 com.albertshao.ds.array.Node@1fb8ee3 com.albertshao.ds.array.Node@61de33 com.albertshao.ds.array.Node@14318bb com.albertshao.ds.array.Node@ca0b6
// Data Structures with Java // by John R. Hubbard and Anita Huray // Copyright 2004 by Prentice Hall package com.albertshao.ds.array; public class TestInsert { TestInsert() { Node start = init(); print(start); insert(start, 50); print(start); } Node init() { Node start = new Node(22), p = start; for (int i=1; i<5; i++) p = p.next = new Node(22+11*i); return start; } void print(Node start) { for (Node p=start; p!=null; p=p.next) System.out.print(p.data + " "); System.out.println(); } void insert(Node start, int x) { // PRECONDITIONS: the list is in ascending order, and x > start.data; // POSTCONDITIONS: the list is in ascending order, and it contains x; Node p = start; while (p.next != null) { if (p.next.data > x) break; p = p.next; } p.next = new Node(x,p.next); } public static void main(String[] args) { new TestInsert(); } class Node { private int data; private Node next; public Node(int data) { this.data = data; } public Node(int data, Node next) { this.data = data; this.next = next; } } } /* Output: 22 33 44 55 66 22 33 44 50 55 66 */
Node delete(Node start, int x) { // precondition: the list is in ascending order; // postconditions: the list is in ascending order, and if it did // contains x, then the first occurrence of x has been deleted; if (start == null || start.data > x) return start; // x is not in the list if (start.data==x) return start.next; for (Node p = start; p.next != null; p = p.next) { if (p.next.data > x) break; // x is not in the list if (p.next.data == x) { p.next = p.next.next; // delete x break; } } return start; }