Data Structures & Algorithms(second:sort)

4 篇文章 0 订阅
3 篇文章 0 订阅

排序:对一种抽象数据类型按照其自然规律或逻辑规律排序(eg:从小到大,从前到后…)
sort:sorting is the processing of rearranging a sequence of objects so as to put them in a logical order.

There are three reasons to study sorting algorithms :

1: A easy start to start all kinds of other algorithms
2:Exercise a ability to compare with other algorithms
3: Similar techniques in other problems

Seven kinds of sorting algorithms :

algorithmstable?in place?order of running timeextra spacenotes
算法稳定性?是否在原数组中操作?时间复杂度额外空间大小注意
selection sortnoyesN^21none
insertion sortyesyesN~N^21time depends on original order of items
shellsortnoyesNlogN or N^(6/5)1none
quicksortnoyesNlogNlgNprobabilistic (概率性的)
3-way quicksortnoyesN~NlogNlgNprobabilistic and depends on what kinds of intput source
mergesortyesnoNlogNNnone
heapsortnoyesNlogN1none

一:selection sort

It is the simplest sorting algorithms .
Its core logic is a for-loop.

core codes :

public static void sort(Comparable[] a) {
		int N=a.length;
		for (int i = 0; i <N; i++) {
			int min =i;
			for(int j=i+1;j<N;j++) {
				if(less(a[j], a[min]))
					min=j;
			}
			exch(a, i,min);
		}
	}

complete codes:

package algorithms_4th_chapter2_1;

import edu.princeton.cs.algs4.In;
/**
 * 2.1
 * O(time)=N^2
 * @author Enzo
 *
 */
public class Selection {
	
	public static void sort(Comparable[] a) {
		int N=a.length;
		for (int i = 0; i <N; i++) {
			int min =i;
			for(int j=i+1;j<N;j++) {
				if(less(a[j], a[min]))
					min=j;
			}
			exch(a, i,min);
		}
	}
	public static boolean less (Comparable v,Comparable w) {
		return  v.compareTo(w)<0;
	}
	public static void exch (Comparable[] a,int i,int j) {
		
		Comparable t=a[i];
		a[i]=a[j];
		a[j]=t;
	}
	public static void show(Comparable [] a) {
		for(int i=0;i<a.length;i++) {
			System.out.print(a[i]+"");
		}
		System.out.println();
	}
	public static boolean is_sorted (Comparable [ ] a) {
		for (int i = 0; i < a.length-1; i++) {
			if(less(a[i+1], a[i]))
				return false;
		}
		return true;
	}
	

	public static void main(String[] args) {
			// TODO Auto-generated method stub
		String[] a =new  In("tiny.txt").readAllStrings();
		sort(a);
		assert is_sorted(a);
		show(a);
		
	}

}

Nodes:
Use Comparable interface
在这里插入图片描述

Every loop to find the minimum item in array and decrease 1 of needed to retrieval array items ,also put this min item in a[i].


Features:
1: Running time is insensitive to input
2: Data move is minimal

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值