1、一维数组的排序
冒泡排序算法:
口诀:
N个数字来排序
两两相比小靠前
外层循环N-1
内层循环N-1-i代码:
for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length-1-i; j++) { if(arr[j] < arr[j+1]){ double temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } }
2、一维数组的查找
1、线性查找算法
2、二分法/二叉搜索算法——先排序,再查找
int[] arr = {63,81,45,18,7}; //排序 - 7,18,45,63,81 Arrays.sort(arr); int num = 81; int start = 0; int end = arr.length-1; while(start <= end){ int mid = (start + end)/2; if(num > arr[mid]){ start = mid+1; }else if(num < arr[mid]){ end = mid-1; }else{ System.out.println("查找到该元素了:" + mid); break; } }
3、一维数组的复制、扩容、删除
1)复制
(1)一维数组的复制1 -- 浅表复制
缺点:修改源数组,新数组的数据也会发生改变
//源数组 String[] arr = {"田","水","花","草"}; //新数组 String[] newArr = arr; //改变源数组 arr[1] = "树"; //遍历新数组 for(String element : newArr){ System.out.println(element); }
(2)一维数组的复制2 -- 深表复制
优点:修改源数组,新数组的数据也不会发生改变
//源数组 String[] arr = {"田","水","花","草"}; //新数组 String[] newArr = new String[arr.length]; //将源数组中所有的元素赋值给新数组 for(int i = 0;i<arr.length;i++){ newArr[i] = arr[i]; } //改变源数组 arr[1] = "树"; //遍历新数组 for(String element : newArr){ System.out.println(element); }
2)扩容
需求:扩容为原来数组长度的1.5倍//源数组 String[] arr = {"田","水","花","草"}; //计算长度 int oldCapacity = arr.length; int newCapacity = oldCapacity + (oldCapacity>>1);
3)删除
(1)一维数组的删除1:
缺点:这种删除会让数组的空间越变越小,没有考虑到以后可能会添加元素
//源数组 String[] arr ={"田","水","花","草"}; //新数组 String[] newArr = new String[arr.length-1]; //将源数组中除了"水"的元素,赋值到新数组中 int index = 0; for(int i = 0;i<arr.length;i++){ if(!arr[i].equals("水")){ newArr[index] = arr[i]; index++; } } //将新数组的地址赋值给源数组 arr = newArr; //遍历源数组 for(String element:arr){ System.out.println(element); }
(2)一维数组的删除2:
这种删除不会让数组的空间越变越小,考虑到以后可能会添加元素
//源数组 String[] arr ={"田","水","花","草"}; //把要删除的元素后面的元素往前移 -- ["田","水","花","草"] for(int i = 1;i<arr.length-1;i++){ arr[i] = arr[i+1]; } //把最后一个元素赋值为null arr[arr.length-1] = null; //遍历源数组 for(String element:arr){ System.out.println(element); }