JAVA进阶19

1、冒泡排序

 package cn.zh.abstrac;

 import java.util.Arrays;

 //冒泡排序
public class Demo019 {
public static void main(String[] args) {
int[] values = {22, 11, 33, 2, 4, 5, 66, 55, 44};
int temp = 0;
for (int j = 0; j < values.length - 1 - j; j++) {
boolean flag = true;
for (int i = 0; i < values.length - 1; i++) {
//比较大小,换顺序
if (values[i] > values[i + 1]) {
temp = values[i];
values[i] = values[i + 1];
values[i + 1] = temp; flag = false;
}
}
if (flag) {
break;
}
}
System.out.println(Arrays.toString(values));
}
}

运行结果图

JAVA进阶19

2、二分法查找法

 package cn.zh.abstrac;

 import java.util.Arrays;

 //二分法查找
public class TestBinarySearch {
public static void main(String[] args) {
int[] arr = {30, 20, 50, 10, 80, 9, 7, 12, 100, 40, 8};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
System.out.println(myBinarySearch(arr,40));
} public static int myBinarySearch(int[] arr, int value){
int low = 0;
int high = arr.length - 1; while (low <= high) {
int mid = (low + high) / 2;
if (value == arr[mid]) {
return mid;
}
if (value > arr[mid]) {
low = mid + 1;
}
if (value < arr[mid]) {
high = mid - 1;
}
}
return -1;
}
}

运行结果图

JAVA进阶19

3、可变字符序列与不可变字符序列

注:循环累加用StringBuilder

 package cn.zh.abstrac;

 public class TestStringBuilder {
public static void main(String[] args) {
//使用String进行字符串的拼接
String str1 = "";
//本质上使用StringBuilder拼接,但是每次循环都会生成一个StringBuilder对象
long num1 = Runtime.getRuntime().freeMemory(); //获取系统剩余内存空间
//获取系统的当前时间
long time1 = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
//相当于产生了10000个对象
str1 = str1 + i;
}
long num2 = Runtime.getRuntime().freeMemory();
long time2 = System.currentTimeMillis();
System.out.println("String占用内存:" + (num1 - num2));
System.out.println("String占用时间:" + (time2 - time1)); //使用StringBuilder进行字符串的拼接
StringBuilder sb1 = new StringBuilder("");
long num3 = Runtime.getRuntime().freeMemory();
long time3 = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
sb1.append(i);
}
long num4 = Runtime.getRuntime().freeMemory();
long time4 = System.currentTimeMillis();
System.out.println("StringBuilder占用内存:" + (num3 - num4));
System.out.println("StringBuilder占用时间:" + (time4 - time3));
}
}

运行结果图

JAVA进阶19

4、

上一篇:Linux学习笔记(二)——文件/目录/VIM


下一篇:Spring 上传文件