数组
====
JAVA中数组可以理解为容器, 使用存储数据。
定义数组有三个方式:
第一种:直接创建一个指定大小的数组
数据类型 [] 数组名 = new 数据类型[数组长度];
第二种:直接创建一个指定值的数组
数据类型 [] 数组名 = {值1,值2,值3,...};
第三种:通过new来创建数组,并且指定值。
数据类型 [] 数组名 = new 数据类型[]{值1,值2,值3,...};
先声明数组名
数据类型 [] 数组名;
数组名 = new 数据类型[数组的长度];
我们要强调, 数组的长度是固定的。 数组会有多维数组, 这就是数组的数组的数组。
二维数组是比如一维数组的数组。
数组会有排序, 我们辨别四种排序:
- 冒泡排序: 它的方法是:
public int[] maopao(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[j] > array[i]) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
- 选择排序: 方法是:
public int[] xuanze(int[] array) {
for (int i = 0; i < array.length; i++) {
int lowerindex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[lowerindex]) {
lowerindex = j;
}
}
int temp = array[i];
array[i] = array[lowerindex];
array[lowerindex] = temp;
}
return array;
}
- 插入排序: 方法是:
public int[] charu(int[]array){
for (int i = 1; i<array.length;i++){
for( int j= i; j>0;j--){
if(array[j]<array[j-1]){
int temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
return array;
}
- 希尔排序(shell 排序):
public int[] shell (int[]array){
for(int increment = array.length/2;increment > 0; increment /=2){
for(int i = increment; i<array.length;i++){
int temp = array[i];
int j = 0;
for(j = i; j>= increment; j-= increment){
if( temp <array[j-increment]){
array[j]= array[j-increment];
}else{
break;
}
} array[j] = temp;
}
}
return array;
}
====
JAVA中数组可以理解为容器, 使用存储数据。
定义数组有三个方式:
第一种:直接创建一个指定大小的数组
数据类型 [] 数组名 = new 数据类型[数组长度];
第二种:直接创建一个指定值的数组
数据类型 [] 数组名 = {值1,值2,值3,...};
第三种:通过new来创建数组,并且指定值。
数据类型 [] 数组名 = new 数据类型[]{值1,值2,值3,...};
先声明数组名
数据类型 [] 数组名;
数组名 = new 数据类型[数组的长度];
我们要强调, 数组的长度是固定的。 数组会有多维数组, 这就是数组的数组的数组。
二维数组是比如一维数组的数组。
数组会有排序, 我们辨别四种排序:
- 冒泡排序: 它的方法是:
public int[] maopao(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[j] > array[i]) {
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
- 选择排序: 方法是:
public int[] xuanze(int[] array) {
for (int i = 0; i < array.length; i++) {
int lowerindex = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[lowerindex]) {
lowerindex = j;
}
}
int temp = array[i];
array[i] = array[lowerindex];
array[lowerindex] = temp;
}
return array;
}
- 插入排序: 方法是:
public int[] charu(int[]array){
for (int i = 1; i<array.length;i++){
for( int j= i; j>0;j--){
if(array[j]<array[j-1]){
int temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
}
}
}
return array;
}
- 希尔排序(shell 排序):
public int[] shell (int[]array){
for(int increment = array.length/2;increment > 0; increment /=2){
for(int i = increment; i<array.length;i++){
int temp = array[i];
int j = 0;
for(j = i; j>= increment; j-= increment){
if( temp <array[j-increment]){
array[j]= array[j-increment];
}else{
break;
}
} array[j] = temp;
}
}
return array;
}