java算法题

1.排序

1.1.实例

@Test

public void tests() {

int[] numbers = { 3, 2, 20, 54, 10, 5, 78, 1, 100 };

int tmep = 0;

for (int i = 0; i < numbers.length; i++) {

for (int j = 0; j < numbers.length - i - 1; j++)

if (numbers[j] > numbers[j + 1]) {

tmep = numbers[j];

numbers[j] = numbers[j + 1];

numbers[j + 1] = tmep;

}

}

for (int n = 0; n < numbers.length; n++) {

System.out.print(numbers[n] + ",");

}

System.out.println("===============");

for (int m = numbers.length - 1; m >= 0; m--) {

System.out.print(numbers[m] + ";");

}

System.out.println("list结果:===============");

List<Integer> list = new ArrayList<Integer>();

for (int a = 0; a < numbers.length; a++) {

list.add(numbers[a]);

}

Collections.sort(list);

for (Integer str : list) {

System.out.print(str + ";");

}

}

1.2.实例

public static void main(String[] arg){

Comparable []num={4,9,12,3,2,45,89};

insertionSort(num);

for(int i=0;i<num.length;i++){

System.out.print(num[i]+",");

}

}

public static void insertionSort(Comparable []data){

for(int index=1;index<data.length;index++){

Comparable key =data[index];

int position=index;

while(position>0 && data[position-1].compareTo(key)>0){

data[position]=data[position-1];

position--;

}

data[position]=key;

}

}

2.求素数

@Test

public void testNum() {

for (int m = 2; m < 100; m++) {

int n;

for (n = 2; n <= (int) (Math.sqrt(m)); n++) {

if (m % n == 0) {

break;

}

}

if (n > (int) (Math.sqrt(m))) {

System.out.print(m + ";");

}

}

System.out.println("==============");

for (int i = 2; i < 100; i++) {

int j;

for (j = 2; j <= i / 2; j++) {

if (i % j == 0) {

break;

}

}

if (j > i / 2) {

System.out.print(i + ";");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值