`
anna_zr
  • 浏览: 200522 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

选择排序和冒泡排序

J# 
阅读更多
简单的实现下选择排序和冒泡排序

1、选择排序
public class NumSort {
public static void main(String args[]){
int[] a = new int[args.length];
for(int i=0; i<args.length;i++){
a[i] = Integer.parseInt(args[i]);
}
print(a);
selectionSort(a);
print(a);
}

private static void selectionSort(int[] a){
int k, temp;
for(int i=0; i<a.length; i++){
k = i;   //一种优化,不必对每次比较结果交换顺序
for(int j=k+1; j<a.length; j++){
if(a[j]<a[k]){
k = j;
}
}
if(k != i){
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
}


private static void print(int[] a){
for(int i=0; i<a.length; i++){
System.out.print(a[i] + " ");
}
System.out.println();
}

}


2、冒泡排序

   对Date型数据排序


public class TestDateSort {
public static void main(String args[]){
Date[] days = new Date[5];
days[0] = new Date(2006, 5, 4);
days[1] = new Date(2006, 7, 4);
days[2] = new Date(2008, 5, 4);
days[3] = new Date(2004, 5, 9);
days[4] = new Date(2004, 5, 4);

bubbleSort(days);

for(int i=0; i<days.length; i++){
System.out.println(days[i]);
}
}

public static Date[] bubbleSort(Date[] a){
int len = a.length;
for(int i = len-1; i>=1; i--){
for(int j = 0; j<=i-1; j++){
if(a[j].compare(a[j+1])>0){
Date temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
}

class Date{
int year, month, day;

Date(int y, int m, int d){
year = y; month = m; day = d;
}

public int compare(Date date){
return year > date.year ? 1
: year < date.year ? -1
: month > date.month ? 1
: month < date.month ? -1
: day > date.day ? 1
: day < date.day ? -1 : 0;
}

public String toString(){
return "Year:Month:Day -- " + year + "-" + month + "-" +day;
}
}


P:纯属菜鸟练手,贴此做复习之用
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics