Java語言基礎 陣列的排序演算法
阿新 • • 發佈:2019-02-09
public
class
VarDemo
{
//氣泡排序static void bubbleSort(int [] arr)
{
for(int times=1;times <= arr.length-1;times++)
{
for(int i=1;i<=arr.length-1;i++)
{
if(arr[i-1]<arr[i])
swap(arr,i-1,i);
}
}
}
//選擇排序static void selectSort(int[] arr)
{
for (int index=0;index<=arr.length - 1;index++)
{
for(int i=0
;i <=arr.length
- 1 ;i++)
if(arr[index]]]>arr[i])
swap(arr,index,i);
}
}
static void swap (int [] arr,int index1, int index2 )
{
int temp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=temp;
}
static void arrPrint(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]);
}
System.out.println();
}
public
static
void
main(String[]
args)
{
int [] arr1 = {2,3,4,5,1,3,6,7};
VarDemo.arrPrint(arr1);
VarDemo.selectSort(arr1);
VarDemo.arrPrint(arr1);
}
}
{
//氣泡排序static void bubbleSort(int [] arr)
{
for(int times=1;times <= arr.length-1;times++)
{
for(int i=1;i<=arr.length-1;i++)
{
if(arr[i-1]<arr[i])
swap(arr,i-1,i);
}
}
}
//選擇排序static void selectSort(int[] arr)
{
for (int index=0;index<=arr.length - 1;index++)
{
for(int i=0
;i
if(arr[index]]]>arr[i])
swap(arr,index,i);
}
}
static void swap (int [] arr,int index1, int index2 )
{
int temp=arr[index1];
arr[index1]=arr[index2];
arr[index2]=temp;
}
static void arrPrint(int arr[])
{
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]);
}
System.out.println();
}
{
int [] arr1 = {2,3,4,5,1,3,6,7};
VarDemo.arrPrint(arr1);
VarDemo.selectSort(arr1);
VarDemo.arrPrint(arr1);
}
}