JAVA冒泡排序(BubbleSort)代码

class BubbleSort 
{
	public static void main(String[] args) 
	{

		int[] arr = new int[]{1,6,3,34,3,54,7,66,19};
		System.out.print("sort the array:");
		printArr(arr);
		System.out.print("sort result is:");
		printArr(bubbleSort(arr));

	}//end of method main

	//冒泡排序法(Buuble sort)
	public static int[] 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])
				{
					int temp = arr[y];
					arr[y] = arr[y+1];
					arr[y+1] = temp;
				}
			}
		}
		return arr;

	}//end of method bubbleSort

	//打印一个数组
	public static void printArr(int[] arr)
	{
		for (int x = 0; x<arr.length; x++ )
		{
			if (x == arr.length - 1)
			{
				System.out.println(arr[x]);
				break;
			}
			System.out.print(arr[x] + ",");
		}
	}//end of method printArr

}//end of class BubbleSort

 

你可能感兴趣的:(Java冒泡排序)