排序算法 博客分类: java内功 简单排序算法
程序员文章站
2024-03-14 08:34:28
...
public static void 我的冒泡(){ int [] arr = {4,9,23,1,45,27,5,2}; for(int i=0;i<arr.length-1;i++){ for(int j=0;j<arr.length-i-1;j++){ if(arr[j] < arr[j+1]){ int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for(int i=0;i<arr.length-1;i++){ System.out.println(arr[i]); } }
public static void 选择排序自己实现的(){ int [] arr = {4,9,23,1,45,27,5,2}; for(int i =0;i<arr.length-1;i++){ int numindex = i; for(int j=i+1;j<arr.length;j++){ if(arr[numindex]<arr[j]){ numindex = j;//获取大值 所以是倒叙 } } int temp = arr[i]; arr[i] = arr[numindex]; arr[numindex] = temp; } for(int i =0;i<arr.length;i++){ System.out.println(arr[i]); } }
public static void 插入排序(Comparable []data){ //int [] arr = {4,9,23,1,45,27,5,2}; for(int index=1;index<data.length;index++){ Comparable key = data[index]; int position = index; while(position>0 && data[position-1].compareTo(key)>0){ data[position] = data[position-1]; position--; } data[position]=key; } }
对象排序 /** * Project Name:ThinkinJava * File Name:User.java * Package Name:org.cf.guott.java.beansort * Date:2013-10-29下午04:22:27 * Copyright (c) 2013, cfguott@126.com All Rights Reserved. * */ package org.cf.guott.java.beansort; /** * ClassName:User <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2013-10-29 下午04:22:27 <br/> * @author gtt * @version * @since JDK 1.6 * @see */ public class User { private int age; private String name; public User(int age,String name){ this.age = age; this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void displayUser(){ System.out.println("age="+age+";name="+name); } } /** * Project Name:ThinkinJava * File Name:UserArr.java * Package Name:org.cf.guott.java.beansort * Date:2013-10-29下午04:23:21 * Copyright (c) 2013, cfguott@126.com All Rights Reserved. * */ package org.cf.guott.java.beansort; /** * ClassName:UserArr <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2013-10-29 下午04:23:21 <br/> * @author gtt * @version * @since JDK 1.6 * @see */ public class UserArr { private User[] users; private int nElems; public UserArr(int max){ users = new User[max]; nElems = 0; } public void insert(int age,String name) { users[nElems] = new User(age,name); nElems ++; } public void display(){ for(int i =0;i<nElems;i++){ users[i].displayUser(); } } public void userSort(){ for(int out = 1;out<nElems;out++){ User u = users[out]; int in = out; while(in > 0 && users[in - 1].getAge() > users[in].getAge()){ users[in] = users[in -1]; in --; } users[in]=u; } } public static void main(String[] args) { UserArr arr = new UserArr(3); arr.insert(15,"aaa"); arr.insert(27,"bbb"); arr.insert(12,"ccc"); arr.userSort(); arr.display(); } }
输出: age=15;name=aaa age=12;name=ccc age=27;name=bbb