Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Scott Dunning Newsgroups: comp.lang.java.programmer Subject: Re: Help with java insertion sort program Date: Sat, 09 Aug 2014 21:11:45 -0700 Organization: A noiseless patient Spider Lines: 78 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 10 Aug 2014 04:08:48 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="11828741c91d0da908948c6ecdf164c7"; logging-data="6436"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18XMnr+30OICJZYXtL7Dc7J9APLpstAuqc=" User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:24.0) Gecko/20100101 Thunderbird/24.6.0 In-Reply-To: Cancel-Lock: sha1:w4jtVaNhI5EmnAGKc3Rq5mrkmmk= Xref: csiph.com comp.lang.java.programmer:29610 Ok so I realized that I was not filling the array with anything but now I'm having issues filling it correctly. It's only filling the array with three of the user inputs and I just cannot figure out why.... import java.util.Scanner; public class DriverSort { public static void main(String[] args) { Scanner scan =new Scanner(System.in); Sorter sorter = new Sorter(); int choice; // variable which says which sorting algorithm to use System.out.println("1-Insertion sort\n" +"2-Selection sort\n" + "3-Bubble sort\n" + "0-quit\n"); choice = scan.nextInt(); System.out.println("Please enter the number for a sorting method or enter 0 to quit: "); int size = scan.nextInt(); int input[] = new int[size]; for(int i = 0; i < size; i++) { input[i] = scan.nextInt(); } System.out.println("\nBefore Sorting: "); Sorter.printArray(input); // sort the array Sorter.insertionSort(input); System.out.println("\nAfter Sorting: "); Sorter.printArray(input); switch (choice) { case 0: System.out.println("Goodbye!"); System.exit(0); break; case 1: Sorter.insertionSort(input); break; } } } import java.util.Arrays; public class Sorter { public static int[] insertionSort(int[] arr) { for (int i = 1; i < arr.length; i++) { int valueToSort = arr[i]; int j = i; while (j > 0 && arr[j - 1] > valueToSort) { arr[j] = arr[j - 1]; j--; }//end while loop. // insert the element arr[j] = valueToSort; }//end for loop return arr; }//end insertionSort public static void printArray(int[] arr) { System.out.println(Arrays.toString(arr)); } }