Java数组排序和插入
2024-10-19 17:45:14
如何排序数组并插入元素?
以下示例显示如何使用sort()
方法和用户定义的insertElement()
方法来完成此任务。
package com.yiibai;
import java.util.*;
public class ArraySortAndInsert {
public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 1);
System.out.println("Didn\'t find 1 @ " + index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
printArray("With 1 added", array);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");
for (int i = 0; i < array.length; i++) {
if (i != 0) {
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
private static int[] insertElement(int original[], int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index + 1, length
- index);
return destination;
}
}
Java
执行上面示例代码,得到以下结果 -
Sorted array: [length: 10]
-9, -7, -3, -2, 0, 2, 4, 5, 6, 8
Didn\'t find 1 @ -6
With 1 added: [length: 11]
-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8
最新文章
- 为什么正常安装并成功运行了Genymotion虚拟但是运行的时候启动的却是自带的模拟器?
- 【使用Unity开发Windows Phone上的2D游戏】(1)千里之行始于足下
- Lists
- Linux卸载系统自带的httpd的方法
- Linux C++服务器程序设计范式
- Light OJ 1030 - Discovering Gold
- 转:Hprose for php(二)——服务器
- C语言函数调用约定
- PS不能存储,因为程序错误
- linux HAProxy及Keepalived热备
- SpringBoot 创建可执行Jar
- HashMap源码分析(基于jdk8)
- C语言面试题分类->;宏定义
- python --端点调试
- TweenMax 动画库,知识点
- activemq jms使用
- 学以致用四----centos7.2 安装python3.6
- mssql循环记录之while方法
- apache2.4配置多个端口对应多个目录
- jdk、tomcat、solr环境搭建
热门文章
- 采用Oracle的dbms_obfuscation_toolkit的加密
- Linux 守护进程
- Lua 自己实现排序sort比较方法,抛出错误invalid order function for sorting
- linux下查看最后登陆的用户的信息
- js判断是否安装flash player及当前版本 和 检查flash版本是否需要升级
- 玩转shell命令行
- ORA-12541:TNS:无监听程序 配置Oracle Myeclipse无法连接上 花费一天时间解决掉的
- Java Web项目部署时 “Exploded Archive”模式部署时无效
- iOS import导入时没有提示的解决办法
- 【转】Java计算文件的hash值