`
MouseLearnJava
  • 浏览: 464047 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

常用排序算法小结

阅读更多

离开课堂后,排序算法写的比较少了,当有排序的要求时,一般用的比较多的是直接采用Arrays.sort以及Collections.sort结合比较器来实现。

Arrays工具类包含了对各种类型数组的排序,以下是Arrays中包括的sort方法:


以下是Collections中的sort方法,该sort方法中结合了Arrays.sort来实现的。
/**
     * Sorts the specified list into ascending order, according to the
     * <i>natural ordering</i> of its elements.  All elements in the list must
     * implement the <tt>Comparable</tt> interface.  Furthermore, all elements
     * in the list must be <i>mutually comparable</i> (that is,
     * <tt>e1.compareTo(e2)</tt> must not throw a <tt>ClassCastException</tt>
     * for any elements <tt>e1</tt> and <tt>e2</tt> in the list).<p>
     *
     * This sort is guaranteed to be <i>stable</i>:  equal elements will
     * not be reordered as a result of the sort.<p>
     *
     * The specified list must be modifiable, but need not be resizable.<p>
     *
     * The sorting algorithm is a modified mergesort (in which the merge is
     * omitted if the highest element in the low sublist is less than the
     * lowest element in the high sublist).  This algorithm offers guaranteed
     * n log(n) performance. 
     *
     * This implementation dumps the specified list into an array, sorts
     * the array, and iterates over the list resetting each element
     * from the corresponding position in the array.  This avoids the
     * n<sup>2</sup> log(n) performance that would result from attempting
     * to sort a linked list in place.
     *
     * @param  list the list to be sorted.
     * @throws ClassCastException if the list contains elements that are not
     *	       <i>mutually comparable</i> (for example, strings and integers).
     * @throws UnsupportedOperationException if the specified list's
     *	       list-iterator does not support the <tt>set</tt> operation.
     * @see Comparable
     */
    public static <T extends Comparable<? super T>> void sort(List<T> list) {
	Object[] a = list.toArray();
	Arrays.sort(a);
	ListIterator<T> i = list.listIterator();
	for (int j=0; j<a.length; j++) {
	    i.next();
	    i.set((T)a[j]);
	}
    }

    /**
     * Sorts the specified list according to the order induced by the
     * specified comparator.  All elements in the list must be <i>mutually
     * comparable</i> using the specified comparator (that is,
     * <tt>c.compare(e1, e2)</tt> must not throw a <tt>ClassCastException</tt>
     * for any elements <tt>e1</tt> and <tt>e2</tt> in the list).<p>
     *
     * This sort is guaranteed to be <i>stable</i>:  equal elements will
     * not be reordered as a result of the sort.<p>
     *
     * The sorting algorithm is a modified mergesort (in which the merge is
     * omitted if the highest element in the low sublist is less than the
     * lowest element in the high sublist).  This algorithm offers guaranteed
     * n log(n) performance. 
     *
     * The specified list must be modifiable, but need not be resizable.
     * This implementation dumps the specified list into an array, sorts
     * the array, and iterates over the list resetting each element
     * from the corresponding position in the array.  This avoids the
     * n<sup>2</sup> log(n) performance that would result from attempting
     * to sort a linked list in place.
     *
     * @param  list the list to be sorted.
     * @param  c the comparator to determine the order of the list.  A
     *        <tt>null</tt> value indicates that the elements' <i>natural
     *        ordering</i> should be used.
     * @throws ClassCastException if the list contains elements that are not
     *	       <i>mutually comparable</i> using the specified comparator.
     * @throws UnsupportedOperationException if the specified list's
     *	       list-iterator does not support the <tt>set</tt> operation.
     * @see Comparator
     */
    public static <T> void sort(List<T> list, Comparator<? super T> c) {
	Object[] a = list.toArray();
	Arrays.sort(a, (Comparator)c);
	ListIterator i = list.listIterator();
	for (int j=0; j<a.length; j++) {
	    i.next();
	    i.set(a[j]);
	}
}


本文将用JAVA实现七个常用排序,包括:冒泡排序,插入排序,选择排序,希尔排序,快速排序,归并排序和堆排序。


代码类图如下:


一个抽象类BsseSort中包含了排序用到的一些公共操作,比如比较等。
package my.sort;

public abstract class BaseSort<T> {

	@SuppressWarnings("hiding")
	protected abstract <T extends Comparable<T>> void sort(T[] array);

	@SuppressWarnings({ "hiding" })
	protected <T extends Comparable<T>> boolean lessThan(T t1, T t2) {
		return t1.compareTo(t2) < 0;
	}

	@SuppressWarnings({ "hiding" })
	protected <T extends Comparable<T>> boolean greatThan(T t1, T t2) {
		return t1.compareTo(t2) > 0;
	}

	@SuppressWarnings("hiding")
	protected <T extends Comparable<T>> boolean equalTo(T t1, T t2) {
		return t1.compareTo(t2) == 0;
	}

	@SuppressWarnings("hiding")
	protected <T extends Comparable<T>> void swap(T[] array, int i, int j) {
		T t = array[i];
		array[i] = array[j];
		array[j] = t;
	}

	@SuppressWarnings("hiding")
	protected <T extends Comparable<T>> void printArray(T[] array) {
		for (T t : array) {
			System.out.print(t);
			System.out.print(" ");
		}
		System.out.println();
	}

}


冒泡排序
package my.sort;

public class BubbleSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		int length = array.length;
		for (int i = 0; i < length; i++) {
			for (int j = 1; j < length - i; j++) {
				if (greatThan(array[j - 1], array[j])) {
					swap(array, j - 1, j);
				}
			}
		}
	}
}


插入排序
package my.sort;

public class InsertionSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		int length = array.length;
		for (int i = 1; i < length; i++) {
			for (int j = i; j > 0 && lessThan(array[j], array[j - 1]); j--) {
				swap(array, j, j - 1);
			}
		}
	}
}


选择排序
package my.sort;

public class SelectionSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		int length = array.length;
		for (int i = 0; i < length; i++) {
			int min = i;
			for (int j = i + 1; j < length; j++) {
				if (lessThan(array[j], array[min])) {
					min = j;
				}
			}
			swap(array, i, min);
		}
	}

}



希尔排序

package my.sort;

public class ShellSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		int length = array.length;
		int h = 1;
		while (h < length / 3) {
			h = 3 * h + 1;
		}
		while (h >= 1) {
			for (int i = h; i < length; i++) {
				for (int j = i; j >= h && lessThan(array[j], array[j - h]); j -= h) {
					swap(array, j, j - h);
				}
			}
			h /= 3;
		}

	}

}

快速排序
package my.sort;

public class QuickSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		sort(array, 0, array.length - 1);
	}

	@SuppressWarnings("hiding")
	private <T extends Comparable<T>> void sort(T[] array, int low, int high) {
		if (high <= low)
			return;
		int j = partition(array, low, high);
		sort(array, low, j - 1);
		sort(array, j + 1, high);
	}

	@SuppressWarnings("hiding")
	private <T extends Comparable<T>> int partition(T[] array, int low, int high) {
		int i = low;
		int j = high + 1;

		T v = array[low];

		while (true) {
			while (lessThan(array[++i], v)) {
				if (i == high)
					break;
			}

			while (lessThan(v, array[--j])) {
				if (j == low)
					break;
			}

			if (i >= j)
				break;

			swap(array, i, j);
		}

		swap(array, low, j);

		return j;

	}
}


归并排序

package my.sort;

/**
 * 自顶向下的归并排序
 * 
 * @author Eric
 * @param <T>
 */
public class MergeSort<T> extends BaseSort<T> {

	@SuppressWarnings("unchecked")
	private Comparable[] aux = null; // 归并所需的辅助数组

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {
		int length = array.length;
		aux = new Comparable[length];
		doSort(array, 0, length - 1);

	}

	@SuppressWarnings("hiding")
	private <T extends Comparable<T>> void doSort(T[] array, int low, int high) {
		if (low < high) {

			// 找出中间索引
			int mid = low + (high - low) / 2;

			// 对左边数组进行递归
			doSort(array, low, mid);

			// 对右边数组进行递归
			doSort(array, mid + 1, high);

			// 合并
			doMerge(array, low, mid, high);
		}

	}

	@SuppressWarnings( { "hiding", "unchecked" })
	private <T extends Comparable<T>> void doMerge(T[] array, int low, int mid,
			int high) {
		// 将array[low...mid]和[mid+1...high]归并
		int i = low;
		int j = mid + 1;

		/* 将array[low...high]复制到aux[low...high] */
		for (int k = low; k <= high; k++) {
			aux[k] = array[k];
		}

		for (int k = low; k <= high; k++) {
			if (i > mid) {
				array[k] = (T) aux[j++];
			} else if (j > high) {
				array[k] = (T) aux[i++];
			} else if (lessThan(aux[j], aux[i])) {
				array[k] = (T) aux[j++];
			} else {
				array[k] = (T) aux[i++];
			}
		}
	}

/*	public static void main(String[] args) {

		String[] array = { "Hello", "World", "Eric", "Allen" };
		MergeSort<String> sort = new MergeSort<String>();
		sort.printArray(array);
		sort.sort(array);
		sort.printArray(array);
	}*/

}


堆排序
package my.sort;

public class HeapSort<T> extends BaseSort<T> {

	@SuppressWarnings("hiding")
	@Override
	protected <T extends Comparable<T>> void sort(T[] array) {

		int length = array.length;

		buildHeap(array, length);

		while (length > 1) {
			length--;
			swap(array, 0, length);
			downHeap(array, length, 0);
		}

	}

	@SuppressWarnings("hiding")
	private <T extends Comparable<T>> void buildHeap(T[] array, int length) {
		for (int v = length / 2 - 1; v >= 0; v--) {
			downHeap(array, length, v);
		}
	}

	@SuppressWarnings("hiding")
	private <T extends Comparable<T>> void downHeap(T[] array, int length, int v) {

		int w = 2 * v + 1;
		while (w < length) {

			if ((w + 1 < length) && greatThan(array[w + 1], array[w])) {
				w++;
			}

			if (!lessThan(array[v], array[w])) {
				return;
			}
			swap(array, v, w);
			v = w;
			w = 2 * v + 1;

		}
	}

}


测试代码比如:   
  public static void main(String[] args) {

	 String[] array = { "Hello", "World", "Eric", "Allen" };
	 HeapSort<String> sort = new HeapSort<String>();
	 sort.printArray(array);
	 sort.sort(array);
	 sort.printArray(array);
     }


下面是几个算法的一些比较。

  • 大小: 47.8 KB
  • 大小: 84.2 KB
  • 大小: 84 KB
2
2
分享到:
评论

相关推荐

    常用排序算法小结(附Java实现)

    这篇博客“常用排序算法小结(附Java实现)”提供了一种深入理解并掌握常见排序算法的途径,尤其对于Java开发者来说非常实用。文章可能涵盖了如冒泡排序、选择排序、插入排序、快速排序、归并排序、堆排序等多种经典...

    各种排序算法小结

    ### 各种排序算法小结 #### 一、引言 排序算法是在计算机科学中非常基础且常用的一类算法。由于在实际应用中往往需要处理大量数据,因此对排序算法的效率有着较高要求。通常,我们会关注算法的时间复杂度来评估其...

    排序算法小结

    排序算法是计算机科学中基础且重要的概念,它们用于组织和整理数据,使得数据按照特定顺序排列。本篇文章将概述几种常见的排序算法,包括快速排序、归并排序、堆排序、Shell排序、插入排序、冒泡排序、交换排序、...

    常见排序算法小结

    在高级语言的执行速度上,c是最快的,c++其次,而java和c#是最后的。Java和c#流行,主要的一个原因是可以跨平台。

    排序算法小结讲解+源码

    ### 排序算法小结讲解+源码 #### 一、引言 排序算法作为计算机科学中的基础且常用算法,在实际应用中具有重要意义。随着数据量的不断增加,对排序算法的效率提出了更高要求。本文将从简单排序算法出发,逐步过渡到...

    分治算法实验(用分治法实现快速排序算法)教学文稿.docx

    六、小结 分治算法是一种有效的算法设计思想,通过将复杂问题分解成小问题,逐步解决,最后合并小问题的解,得到整个问题的解。快速排序算法是基于分治算法的思想,通过将数据分割成独立的两部分,然后递归地对这两...

    Java数组常用排序算法实例小结

    Java数组常用排序算法实例小结 Java数组常用排序算法是每个Java开发者都需要掌握的基本技能,本文将通过实例形式总结分析Java数组常用的四种排序算法,分别是冒泡排序、数组递增排序、快速排序及选择排序。 一、...

    PHP常用排序算法实例小结【基本排序,冒泡排序,快速排序,插入排序】

    本文将详细讲解四种PHP中常用的排序算法:基本排序(通常指的是选择排序或冒泡排序)、冒泡排序、快速排序以及插入排序。 1. **基本排序**(这里可能是指的选择排序):选择排序是一种简单直观的排序算法,它的工作...

    Java排序小结:常用的排序方法

    本篇文章将详细解析Java中常见的排序方法,结合"javaeye 收集的java排序小结"资料,旨在帮助读者理解和掌握这些排序算法。 1. 冒泡排序(Bubble Sort) 冒泡排序是最简单的排序算法之一,通过重复遍历数组,比较...

    Java常用算法手册源代码

    第4章 排序算法 第5章 查找算法 第6章 基本数学问题 第7章 数据结构问题 第8章 数论问题 第9章 算法经典趣题 **0章 游戏中的算法 **1章 密码学概述 **2章 压缩与解压缩算法 第3篇 算法面试篇 **3章 数学能力测试 **4...

    C/C++常用算法手册.秦姣华(有详细书签).rar

    4.5.2 Shell排序算法示例 111 4.6 快速排序法 113 4.6.1 快速排序算法 113 4.6.2 快速排序算法示例 114 4.7 堆排序法 116 4.7.1 堆排序算法 116 4.7.2 堆排序算法示例 121 4.8 合并排序法 123 4.8.1 合并...

    JavaScript常用数组算法小结

    以下是两种常用的实现方式: 1. **每次随机抽一个数并移动到新数组中**: 这种方法通过while循环,每次随机选择一个数组中的元素添加到新数组,然后从原数组中删除。这种方法保证了所有元素最终都会被选中,但删除...

    c语言数据结构抽象数据类型模板库及常用算法C语言的实现毕业论文.docx

    **1.4 本章小结** 本章介绍了研究的背景和意义,以及论文的主要内容和结构,为后续深入探讨C语言中的数据结构、ADT模板库和算法奠定了基础。 **2. 数据结构实现** 在C语言中实现数据结构,需要考虑内存管理、指针...

    Java数组高级算法与Arrays类常见操作小结【排序、查找】

    冒泡排序是一种简单且常用的排序算法。其原理是通过相邻元素两两比较,大的往后放,第一次完毕,最大值出现在了最大索引处。代码实现如下: ```java public class ArrayDemo { public static void main(String[] ...

    华为OD机考小结+算法编程试题一遍过

    【华为OD机考小结及算法编程试题解析】 华为OD机考是华为公司针对软件开发和测试岗位的招聘环节,其重要性不言而喻,因为它直接影响候选人的定级和薪资。机考主要包含三道题目,两道简单,一道中等,涵盖50%的软件...

    java String类常用方法练习小结

    在这个例子中,我们使用冒泡排序算法,通过比较相邻元素并交换位置,最终得到按字典顺序排列的字符串数组。 ```java public class StringTest_1 { // 对字符串数组进行排序 public static void stringSort(String...

    数据结构与算法学习辅导及习题详解.张乃孝版

    在算法部分,排序算法是核心内容,书中详细解析了冒泡排序、选择排序、插入排序、快速排序、归并排序等基础排序算法,以及堆排序和希尔排序等更高效的方法。查找算法方面,书中介绍了顺序查找、二分查找和哈希查找等...

Global site tag (gtag.js) - Google Analytics