Hark的数据结构与算法练习之地精(侏儒)排序
算法说明
地精排序是交换排序的一种,它是冒泡排序的一种改良,我感觉和鸡尾酒排序挺像的。
不同之处是鸡尾酒排序是从小到大,然后再从大到小切换着排序的。而地精排序是上来先从小到大排序,碰到交换到再从大到小,接着再从小到大进行排序。
举个例子:
对8,6,4,5,1进行升序排序
1、8与6交换,结果是
{6,8,4,5,1}
2、8与4交换,结果是
{6,4,8,5,1}
3、4与6交换,结果是
{4,6,8,5,1}
4、5与8交换,结果是
{4,6,5,8,1}
5、6与5交换,结果是
{4,5,6,8,1}
6、8与1交换,结果是
{4,5,6,1,8}
7、6与1交换,结果是
{4,5,1,6,8}
8、5与1交换,结果是
{4,1,5,6,8}
9、4与1交换,结果是
{1,4,5,6,8}
代码
使用的是java
package hark.sort.exchangesort;
/*
 * 地精排序(侏儒排序)
 */
public class GnomeSort {
	public static void main(String[] args) {
		int[] arrayData = { 5, 3, 2, 4, 3, 1, 2, 1, 4, 2, 4, 21, 6, 3, 2, 1 };
		GnomeSortMethod(arrayData);
		for (int integer : arrayData) {
			System.out.print(integer);
			System.out.print(" ");
		}
	}
	public static void GnomeSortMethod(int[] arrayData) {
		int index = 0;
		int temp;
		while (index < arrayData.length - 1) {
			if (arrayData[index] <= arrayData[index + 1]) {
				index++;
			} else {
				temp = arrayData[index];
				arrayData[index] = arrayData[index + 1];
				arrayData[index + 1] = temp;
				if (index > 0) {
					index--;
				} else {
					index++;
				}
			}
		}
	}
}
参考
http://blog.csdn.net/wklken/article/details/7606519
 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号