1.写出程序结果。
class Demo
{
public static void main(String[] args)
{
int x = 1;
for(show('a'); show('b') && x<3; show('c'))
{
show('d');
x++;
}
}
public static boolean show(char ch)
{
System.out.println(ch);
return true;
}
}
//a b d c b d c b
2,
/*swap(方法)
无论什么排序。都需要对满足条件的元素进行位置置换。
可以把这部分相同的代码提取出来,单独封装成一个函数。
*/
public static void swap(int[] arr,int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
选择排序。
内循环结束一次,最值出现头角标位置上。 第一轮下来,最值放在第一位,其他依次类推
*/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])
{/*int temp = arr[x];arr[x] = arr[y];arr[y]= temp;*/swap(arr,x,y);}}}}
/*
冒泡排序(相邻两个元素进行比较,如果符合条件则进行调换,一轮下来,最值放在最后位)
*/
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++)//-x:让每一次比较的元素减少,-1:避免角标越界。
{
if(arr[y]<arr[y+1])
{
/*
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1] = temp;
*/
swap(arr,y,y+1);
}
}
}
}