Insert, Delete, Search, Print an int Array in Java

By: Grant Braught Viewed: 153560 times  Printer Friendly Format    


The sample java program demonstrates sorting an int array. This class contains static methods which implement a number of classic sorting algorithms including: Insertion Sort, Selection Sort and Merge Sort.
public class Sorts {

    /**
     * Method which sorts the array referred to 
     * by a using the insertion sort algorithm.
     *
     * @param a the array to be sorted.
     */
    public static void insertionSort(int[] a) {
	
	// For each element in the array of integers...
	// (Note: the first element will not need to be considered
	//  because it is already in order with respect to itself!)
	for (int loc=1; loc= 0 && a[i] > a[i+1]) {
		int tmp = a[i];
		a[i] = a[i+1];
		a[i+1] = tmp;
		i--;
	    }
	}
    }
    
    /**
     * Method which sorts the array referred to 
     * by a using the selection sort algorithm.
     *
     * @param a the array to be sorted.
     */
    public static void selectionSort(int[] a) {
	
	// For each element in the array of integers...
	// (Note: the final element will not need to be considered
	//  because by the the time it would be considered the array
	//  will already be correctly sorted.)
	for(int loc=0; loc= left.length) {
	    // The left array has been use up...
	    rest = right;
	    restIndex = rightIndex;
	}
	else {
	    // The right array has been used up...
	    rest = left;
	    restIndex = leftIndex;
	}

	// Copy the rest of whichever array (left or right) was
	// not used up.
	for (int i=restIndex; i                                        

Most Viewed Articles (in Java )

Latest Articles (in Java)

Comment on this tutorial