如何排序数组并插入元素?

以下示例显示如何使用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

最新文章

  1. 为什么正常安装并成功运行了Genymotion虚拟但是运行的时候启动的却是自带的模拟器?
  2. 【使用Unity开发Windows Phone上的2D游戏】(1)千里之行始于足下
  3. Lists
  4. Linux卸载系统自带的httpd的方法
  5. Linux C++服务器程序设计范式
  6. Light OJ 1030 - Discovering Gold
  7. 转:Hprose for php(二)——服务器
  8. C语言函数调用约定
  9. PS不能存储,因为程序错误
  10. linux HAProxy及Keepalived热备
  11. SpringBoot 创建可执行Jar
  12. HashMap源码分析(基于jdk8)
  13. C语言面试题分类-&gt;宏定义
  14. python --端点调试
  15. TweenMax 动画库,知识点
  16. activemq jms使用
  17. 学以致用四----centos7.2 安装python3.6
  18. mssql循环记录之while方法
  19. apache2.4配置多个端口对应多个目录
  20. jdk、tomcat、solr环境搭建

热门文章

  1. 采用Oracle的dbms_obfuscation_toolkit的加密
  2. Linux 守护进程
  3. Lua 自己实现排序sort比较方法,抛出错误invalid order function for sorting
  4. linux下查看最后登陆的用户的信息
  5. js判断是否安装flash player及当前版本 和 检查flash版本是否需要升级
  6. 玩转shell命令行
  7. ORA-12541:TNS:无监听程序 配置Oracle Myeclipse无法连接上 花费一天时间解决掉的
  8. Java Web项目部署时 “Exploded Archive”模式部署时无效
  9. iOS import导入时没有提示的解决办法
  10. 【转】Java计算文件的hash值