6-4 xcu-sjjg-java-List-4 相邻元素交换将最大值移到最后
设计一个算法,通过相邻两个元素的交换的方法,将非空顺序表L中的最大元素移动到最后(最大元素唯一)
函数接口定义:
方法接口
public void move()
裁判测试程序样例:
import java.util.Scanner;
class SqList
{
int [] listElem;
int curLen;
public SqList( ) // 创建n个元素构造的顺序表
{
Scanner sc = new Scanner(System.in);
this.listElem = new int[100];
int n = sc.nextInt();
for(int i = 0 ; i<n ;i++ )
{
this.listElem[i] = sc.nextInt();
}
this.curLen = n;
}
//输出所有元素
public void display()
{
int i;
for( i = 0 ; i <this.curLen ; i++)
{
System.out.print( this.listElem[i]+" ");
}
}
/* 请在这里填写答案 */
}
public class Main{
public static void main(String args[]){
SqList L = new SqList( );
L.move();
L.display();
}
}
输入样例:
输入一行n+1个整数 ,第一个是线性表长度,接下来的n个整数是线性表的元素。
5 2 1 7 4 3
结尾无空行
输出样例:
1 2 4 3 7
结尾无空行
public void move() {
for (int i = 0; i < curLen - 1; i++) {
if (listElem[i] > listElem[i + 1]) {
int temp = listElem[i];
listElem[i] = listElem[i + 1];
listElem[i + 1] = temp;
}
}
}