欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Test

程序员文章站 2022-05-30 16:10:21
...
BUBBLE(new Sortable() {
		public <T extends Comparable<T>> void sort(T[] array, boolean ascend) {
			int length = array.length;
			int lastExchangedIdx = 0;
			for (int i = 0; i < length; i++) {
				// mark the flag to identity whether exchange happened to false
				boolean isExchanged = false;
				// last compare and exchange happened before reaching index i
				int currOrderedIdx = lastExchangedIdx > i ? lastExchangedIdx : i;
				for (int j = length - 1; j > currOrderedIdx; j--) {
					int compare = array[j - 1].compareTo(array[j]);
					if (compare != 0 && compare > 0 == ascend) {
						exchange(array, j - 1, j);
						isExchanged = true;
						lastExchangedIdx = j;
					}
				}
				// if no exchange happen means array is already in order
				if (isExchanged == false) {
					break;
				}
			}
		}
	}),
相关标签: exchange