Java中简单的2个排序(冒泡排序,选择排序)
用Arrays带有的排序方法快速排序
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy6357')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy6357>import java.util.Arrays;
public class Test2{
public static void main(String[] args){
int[] a={5,4,2,4,9,1};
Arrays.sort(a); //进行排序
for(int i: a){
System.out.print(i);
}
}
}
插入排序算法
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy7572')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy7572>
public static int[] insertSort(int[] args){//插入排序算法
for(int i=1;i<args.length;i ){
for(int j=i;j>0;j--){
if (args[j]<args[j-1]){
int temp=args[j-1];
args[j-1]=args[j];
args[j]=temp;
}else break;
}
}
return args;
}
冒泡排序:
<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy3559')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy3559>public static void bubbleSort(int[] arr){
for(int x=0;x<arr.length-1;x ){
for(int y=0;y<arr.length-x-1;y ){
if(arr[y]>arr[y 1]){
swap(arr, y, y 1);
}
}
}
}
/**
* 换位操作
* @param arr传入的数组
* @param a
* @param b
*/
private static void swap(int[] arr,int a ,int b){
int temp=arr[a];
arr[a]=arr[b];
arr[b]=temp;
}
选择排序:
/***
* @param arr 传入的数组
* 选择排序
*/ public static void selectSort(int[] arr){
for(int x=0;x<arr.length-1;x ){
for(int y=x 1;y<arr.length;y ){
if(arr[x]<arr[y]){
swap(arr, x, y);
}
}
}
}
您可能感兴趣的文章:
php 实现冒泡排序的简单例子
php 冒泡排序的实现代码
java排序算法
php 选择排序的实现代码
php冒泡排序的小例子
php冒泡排序算法实现代码
javascript排序算法代码解析
php数组排序方法大全(脚本学堂整理奉献)
php实用快速排序算法的实例代码
php 数组排序方法分享(冒泡排序、选择排序)