java - Using insertion sort to sort only part of array -
i'm writing quicksort program. part of quicksort involves using insertionsort, sorts range of elements, since quicksort handles rest. i'm trying emulate method provided textbook uses
public static void insertionsort(int a[], int left, int right) but struggling figure out how left , right used. here insertionsort code without using parameters left , right:
public static void insertionsort(int a[], int left, int right) { int j; (int p = 1; p < a.length; p++) { int tmp = a[p]; for(j = p; j > 0 && tmp < a[j - 1]; j--) { a[j] = a[j-1]; } a[j] = tmp; } } if add left , right parameters sort part of array, apply?
thanks help.
use left , right in loop declaration:
public static void insertionsort(int a[], int left, int right) { int j; (int p = left; p < right; p++) { int tmp = a[p]; for(j = p; j > 0 && tmp < a[j - 1]; j--) { a[j] = a[j-1]; } a[j] = tmp; } } example input: insertionsort({3, 2, 6, 5, 8, 3, 6, 7, 0}, 2, 6)
example output: {3, 2, 3, 5, 6, 8, 6, 7, 0}
edit:
in above example, left inclusive , right exclusive. if want include right index, change p < right p<= right. keep in mind when calling method indexing starts @ 0.
Comments
Post a Comment