import java.util.Random;
/**
* Copyright 2015年5月2日 by
*
* All Rights Reserved
*
* @Package
* @Title: BubbleSort.java
* @author
* @date 2015年5月2日 上午9:53:17
*/
public class BubbleSort
{
public static void main(String arg[])
{
int k = 0;
while (k < 10000)
{
BubbleSort bubbleSort = new BubbleSort();
int[] sortedArray = bubbleSort.createIntArrays(new Random(), 10);
// int[] sortedArray={783621832 ,-86041034
// ,1575632393,-625778470};//1575632393, 2064581627, -625778470
// ,1512449990 ,770640410 ,-1231559618};
System.out.println("\n 排序前的数组:");
bubbleSort.printArray(sortedArray);
int[] haveSoredArray = bubbleSort.sort(sortedArray);
System.out.println("\n 排序后的数组:");
bubbleSort.printArray(haveSoredArray);
if (bubbleSort.isSortedArray(haveSoredArray))
{
System.out.println("\n 排序算法正确");
}
else
{
System.err.println("\n 排序算法错误");
}
k++;
}
}
private int[] sort(int[] sortedArray)
{
if (sortedArray == null || sortedArray.length <= 1)
{
return sortedArray;
}
for (int index = 0, step = 0; step < sortedArray.length - index; index++)
{
int max = sortedArray[0];
for (int nextIndex = 1; nextIndex < sortedArray.length - index; nextIndex++)
{
int nextIndexValue = sortedArray[nextIndex];
if (max > nextIndexValue)
{
int temp = max;
sortedArray[nextIndex - 1] = nextIndexValue;
sortedArray[nextIndex] = temp;
}
else
{
max = nextIndexValue;
}
}
}
return sortedArray;
}
private boolean isSortedArray(int[] test)
{
int i = 0;
int j = 1;
while (j < test.length)
{
if (test[i] > test[j])
{
System.out.println("\n 前一个值:" + test[i] + "大于" + "后一个值:"
+ test[j]);
return false;
}
i++;
j++;
}
return true;
}
private int[] createIntArrays(Random random, int size)
{
int[] intArray = new int[size];
for (int i = 0; i < intArray.length; i++)
{
intArray[i] = random.nextInt();
}
return intArray;
}
private void printArray(int[] t)
{
System.out.println("array size is: " + t.length + " values are:");
for (int i : t)
{
System.out.print(i + " ");
}
}
}
冒泡排序算法
最新推荐文章于 2023-12-26 20:29:03 发布