Java Algorithms Sort Insertion Sort

Description

Java Algorithms Sort Insertion Sort


class MyArray {/*from ww w  . ja  va  2 s.  c o m*/
   private long[] a; // ref to array a
   private int nElems; // number of data items

   public MyArray(int max) {
      a = new long[max]; // create the array
      nElems = 0; // no items yet
   }

   public void insert(long value) {
      a[nElems] = value; // insert it
      nElems++; // increment size
   }

   public void display() {
      for (int j = 0; j < nElems; j++)
         System.out.print(a[j] + " ");
      System.out.println("");
   }

   public void insertionSort() {
      int in, out;

      for (out = 1; out < nElems; out++) // out is dividing line
      {
         long temp = a[out]; // remove marked item
         in = out; // start shifts at out
         while (in > 0 && a[in - 1] >= temp) // until one is smaller,
         {
            a[in] = a[in - 1]; // shift item to right
            --in; // go left one position
         }
         a[in] = temp; // insert marked item
      }
   }
}

public class Main {
   public static void main(String[] args) {
      int maxSize = 100; // array size
      MyArray arr = new MyArray(maxSize); // create the array

      arr.insert(7); // insert 10 items
      arr.insert(9);
      arr.insert(4);
      arr.insert(5);
      arr.insert(2);
      arr.insert(8);
      arr.insert(1);
      arr.insert(0);
      arr.insert(6);
      arr.insert(3);

      arr.display(); // display items

      arr.insertionSort(); // insertion-sort them

      arr.display(); // display them again
   }
}



PreviousNext

Related