We would like to know how to implement a Insertion Sort.
public class MainClass { public static void main(String[] args) { int[] intArray = new int[] { 2, 6, 3, 8, 4, 9, 1 }; // www .j a v a2s . c o m for (int i : intArray) { System.out.print(i); } System.out.println(); insertionSort(intArray); for (int i : intArray) { System.out.print(i); } } public static void insertionSort(int[] intArray) { int in, out; for (out = 1; out < intArray.length; out++) { int temp = intArray[out]; in = out; while (in > 0 && intArray[in - 1] >= temp) { intArray[in] = intArray[in - 1]; --in; } intArray[in] = temp; } } private static void swap(int[] intArray, int one, int two) { int temp = intArray[one]; intArray[one] = intArray[two]; intArray[two] = temp; } }
The code above generates the following result.
Sort Objects using insertion sort
class Person {/* w w w .ja v a 2s .c om*/ private String lastName; private String firstName; private int age; public Person(String last, String first, int a) { lastName = last; firstName = first; age = a; } public String toString() { return "Last name: " + lastName + " First name: " + firstName + " Age: " + age; } public String getLast() { return lastName; } } public class MainClass { public static void main(String[] args) { Person[] persons = new Person[] { new Person("a", "b", 23), new Person("i", "a", 25), new Person("y", "h", 26), new Person("d", "e", 27) }; System.out.println("Before sorting:"); for (Person p : persons) { System.out.println(p); } insertionSort(persons); System.out.println("After sorting:"); for (Person p : persons) { System.out.println(p); } } public static void insertionSort(Person[] persons) { int in, out; for (out = 1; out < persons.length; out++) { Person temp = persons[out]; in = out; while (in > 0 && persons[in - 1].getLast().compareTo(temp.getLast()) > 0) { persons[in] = persons[in - 1]; --in; } persons[in] = temp; } } }
The code above generates the following result.