有三类书籍0、1、2,存储在顺序表中,按类别进行排序,要求时间复杂度为O(n),空间复杂度为O(1)。给出了书籍和顺序表的结构

105 阅读1分钟
public class BookSort {
    public static void main(String[] args) {
        int list[] = {2, 0, 1, 2, 1, 2, 0, 0, 1, 2, 0, 1, 2};
        list = sort(list);
        for (int i :
                list) {
            System.out.println("i = " + i);
        }
    }

    public static int[] sort(int list[]) {
        int ptr_0 = 0;
        int ptr_2 = list.length - 1;
        int ptr = 1;
        while (list[ptr_0] == 0) {
            ptr_0++;
        }
        while (list[ptr_2] == 2) {
            ptr_2--;
        }
        while (ptr <= ptr_2) {
            if (list[ptr] == 0) {
                swap(list, ptr_0, ptr);
                ptr_0++;
            } else if (list[ptr] == 2) {
                swap(list, ptr_2, ptr);
                ptr_2--;
            } else {
                ptr++;
            }
        }
        return list;
    }

    public static void swap(int list[], int idx_0, int idx_1) {
        int temp = list[idx_0];
        list[idx_0] = list[idx_1];
        list[idx_1] = temp;
    }

}