您的位置:首页 > 编程语言 > Java开发

JAVA算法(直接插入排序)

2009-05-24 22:49 260 查看
世面上的算法书大都是C写的,为了学习JAVA和算法自己写了个JAVA的直接插入排序。由于水平有限,存在很多不足之处,希望大家能够多加指正,谢谢。

/**这是一个利用直接插入排序法写的一个小程序;
直接插入排序是一个将待排序列中的元素p[i]与一个有序序列中的元素q[j--]比较(从后向前),当p[i] >= q[j] (递增排序)或 p[i] <= q[j] (递减排序)时,q[j+1] = p[i];反之就将q[j]移位到q[j+1]为p[i]的插入预留空间且如果j==0则q[j] = p[i].
*/

public class SISort
{
public static int[] sortAscending(int []with){	//整数递增排序
int length = with.length;	//获取待排数组的元素个数;
int []temp = new int[length];
temp[0] = with[0];	//定义一个只有一个元素的有序数组

for(int i=1; i<length; i++){
for(int j=i-1; j>=0;j--){
if(with[i] >= temp[j]){	//如果待排序列中的元素大于等于有有序序列中的元素,则插入
temp[j+1] = with[i];
break;
}
else {
temp[j+1] = temp[j];	//给待插入元素预留空间
if(j == 0)
temp[j] = with[i];	//with[[i]是有序序列中最小的,因此排在开头
}
}
}

return temp;
}

public static double[] sortAscending(double []with){	//带小数的递增排序
int length = with.length;	//获取待排数组的元素个数;
double []temp = new double[length];
temp[0] = with[0];	//定义一个只有一个元素的有序数组

for(int i=1; i<length; i++){
for(int j=i-1; j>=0;j--){
if(with[i] >= temp[j]){	//如果待排序列中的元素大于等于有有序序列中的元素,则插入
temp[j+1] = with[i];
break;
}
else {
temp[j+1] = temp[j];	//给待插入元素预留空间
if(j == 0)
temp[j] = with[i];	//with[[i]是有序序列中最小的,因此排在开头
}
}
}

return temp;
}

public static double[] sortDescending(double []with){	//递减排序
int length = with.length;	//获取待排数组的元素个数;
double []temp = new double[length];
temp[0] = with[0];	//定义一个只有一个元素的有序数组

for(int i=1; i<length; i++){
for(int j=i-1; j>=0;j--){
if(with[i] <= temp[j]){	//如果待排序列中的元素小于等于有有序序列中的元素,则插入
temp[j+1] = with[i];
break;
}
else {
temp[j+1] = temp[j];	//给待插入元素预留空间
if(j == 0)
temp[j] = with[i];	//with[[i]是有序序列中最大的,因此排在开头
}
}
}

return temp;
}

public static int[] sortDescending(int []with){	//递减排序
int length = with.length;	//获取待排数组的元素个数;
int []temp = new int[length];
temp[0] = with[0];	//定义一个只有一个元素的有序数组

for(int i=1; i<length; i++){
for(int j=i-1; j>=0;j--){
if(with[i] <= temp[j]){	//如果待排序列中的元素小于等于有有序序列中的元素,则插入
temp[j+1] = with[i];
break;
}
else {
temp[j+1] = temp[j];	//给待插入元素预留空间
if(j == 0)
temp[j] = with[i];	//with[[i]是有序序列中最大的,因此排在开头
}
}
}

return temp;
}

/*	public static void main(String[] args)
{
int []test1 = {2,6,5,8,7,9,10,256,248,14};	//测试数组
double []test2 = {1.1,2.0,3,5,6,8.9,99,5};
int []temp1;	//中间变量
double []temp2;
temp1 = sortDescending(test1);		//测试整数递减排序
System.out.println("get a Decreasing sequence ");
for(int i=0; i<temp1.length; i++){
System.out.println(temp1[i]);
}

temp1 = sortAscending(test1);		//测试整数递增排序
System.out.println("get a Increasing sequence");
for(int i=0; i<temp1.length; i++){
System.out.println(temp1[i]);
}

temp2 = sortDescending(test2);		//测试带小数递减排序
System.out.println("get a Decreasing sequence ");
for(int i=0; i<temp2.length; i++){
System.out.println(temp2[i]);
}

temp2 = sortAscending(test2);		//测试带小数递增排序
System.out.println("get a Increasing sequence");
for(int i=0; i<temp2.length; i++){
System.out.println(temp2[i]);
}
}*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: