简体   繁体   中英

Using insertion sort to sort only part of array

I'm writing a quicksort program. Part of the quicksort involves using insertionsort, but it only sorts a certain range of elements, since quicksort handles the rest. I'm trying to emulate a method provided by my textbook that uses

   public static void insertionSort(int a[], int left, int right)

But I am struggling to figure out how left and right are used. Here is the insertionsort code without using the parameters left and right:

public static void insertionSort(int a[], int left, int right) {
    int j;
    for (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 I were to add the left and right parameters to help sort only part of the array, where would they apply?

Thanks for the help.

Use left and right in the for loop declaration:

public static void insertionSort(int a[], int left, int right) {
    int j;
    for (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 the above example, left is inclusive and right is exclusive. If you want to include the right index, change p < right to p<= right. Keep in mind when calling the method that indexing starts at 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM