62,615
社区成员
发帖
与我相关
我的任务
分享
package com.cn.sort;
public class FindLastTwo {
public static void main(String[] args) {
int[] a = new int[]{9,10,2,1};
int lastTwoNum = findLastTwo(a);
System.out.println(lastTwoNum);
}
//时间复杂度为O(n)
private static int findLastTwo(int[] a) {
int min = Integer.MAX_VALUE;
int lastTwo = Integer.MAX_VALUE;
if (a.length >= 2) {
if (a[0] < a[1]) {
min = a[0];
lastTwo = a[1];
} else {
min = a[1];
lastTwo = a[0];
}
} else {
return Integer.MIN_VALUE;
}
for (int i = 2; i < a.length; i++) {
if (a[i] < min) {
lastTwo = min;
min = a[i];
} else if (a[i] < lastTwo) {
lastTwo = a[i];
}
}
if (min <= lastTwo) {
return lastTwo;
} else {
return min;
}
}
}
public static void main(String args[]) throws IOException
{
int a[]={19,20,2,4,6,8,29,5,1,30};
boolean flag=true;//true时取最大值,false取最小
int temp; //用于交换
for(int i=0;i<a.length;i++)
{
for(int j=a.length-1;j>=1+i;j--)
{
if(flag&&a[j]>a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
if(!flag&&a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
}
}
flag=!flag;
}
System.out.println(Arrays.toString(a));
}
public class Test {
public static void main(String[] args) {
int[] array = { 5, 2, 6, 4, 3, 1, 8, 10, 9, 7 };
for (int i = 0; i < array.length; i++) {
int flag = (i + 1) % 2;
int tmp = array[i];
int point = i;
for (int j = i; j < array.length; j++) {
if (flag != 0) {
if (array[j] > tmp) {
tmp = array[j];
point = j;
}
} else {
if (array[j] < tmp) {
tmp = array[j];
point = j;
}
}
}
if (i != point) {
array[i] = array[i] ^ array[point];
array[point] = array[i] ^ array[point];
array[i] = array[i] ^ array[point];
}
}
System.out.println(Arrays.toString(array));
}
}