java对⼆维数组排序的⼏种⽅法
public void dAM1() {
int[] a[] = {
{ 12, 26, 89, 78, 45, 65, 36 },
{ 2, 6, 90, 34, 16, 27, 5 },
{ 13, 3, 4, 29, 33, 37, 17 },
{ 1, 9, 19, 49, 57, 22, 11 },
{ 7, 82, 35, 21, 24, 59, 60 } };
for (int i = 0; i < a.length; i++) { // ⼆维数组的长度
for (int j = 0; j < a[i].length; j++) { // 每个⼀维数组的长度
int n = j + 1;
for (int m = i; m < a.length; m++) {
for (; n < a[i].length; n++) {
if (a[i][j] < a[m][n]) {
int max = a[m][n];
a[m][n] = a[i][j];
a[i][j] = max;
}
}
n = 0; // 此处是给n从第⼆个⼀维数组开始取0这个坐标
}
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
// ⼆维数组全部排序
public void dAM2() {
int[][] a = {
{ 12, 26, 89, 78, 45, 65, 36 },
{ 2, 6, 90, 34, 16, 27, 5 },
{ 13, 3, 4, 29, 33, 37, 17 },
{ 1, 9, 19, 49, 57, 22, 11 },
{ 7, 82, 35, 21, 24, 59, 60 } };
int b[] = new int[35]; // new⼀个⼀维数组,数组长度与⼆维数组a的所有元素个数是⼀样的
for (int i = 0; i < a.length; i++) { // ⼆维数组长度
for (int j = 0; j < a[i].length; j++) { // ⼀维数组的长度
b[j + i * (a[i].length)] = a[i][j]; // 将俩维数组赋值给⼀维数组,注意坐标的计算
}
}
for (int i = 0; i < b.length; i++) { // 对⼀维数组进⾏选择排序
for (int j = 0; j < b.length - 1; j++) {
if (b[j] < b[j + 1]) {
int t = b[j];
b[j] = b[j + 1];
b[j + 1] = t;
}
}
}
for (int i = 0; i < a.length; i++) { // 再将排完序的⼀维数组赋值给俩维数组,注意坐标的计算
for (int j = 0; j < a[i].length; j++) {
a[i][j] = b[j + i * (a[i].length)];
}
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
for (int j = 0; j < a[i].length; j++) {
java定义一维数组并赋值System.out.print(a[i][j] + "\t");
}
System.out.println();
}
}
/
/ ⼆维数组全部排序
public void dAM3() {
int[][] b = {
{ 12, 26, 89, 78, 45, 65, 36 },
{ 2, 6, 90, 34, 16, 27, 5 },
{ 13, 3, 4, 29, 33, 37, 17 },
{ 1, 9, 19, 49, 57, 22, 11 },
{ 7, 82, 35, 21, 24, 59, 60 } };
for (int w = 0; w < b.length; w++) { // ⼆维数组的长度
for (int t = 0; t < b[w].length; t++) { // ⼀维数组的长度
for (int i = 0; i < b.length; i++) { // ⼆维数组的长度
for (int j = 0; j < b[w].length; j++) { // ⼀维数组的长度
if (b[w][t] > b[i][j]) { // 套在for循环⾥,俩个⼀模⼀样的数组进⾏⽐较
int max = 0;
max = b[i][j];
b[i][j] = b[w][t];
b[w][t] = max;
}
}
}
}
}
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[i].length; j++) {
System.out.print(b[i][j] + " ");
}
System.out.println();
}
}
// ⽅法四:是对每个单独的数组进⾏由⼩到⼤排序
public void dAM4() { // 对单个的⼀维数组进⾏排序
int[][] a = {
{ 12, 26, 89, 78, 45, 65, 36 },
{ 2, 6, 90, 34, 16, 27, 5 },
{ 13, 3, 4, 29, 33, 37, 17 },
{ 1, 9, 19, 49, 57, 22, 11 },
{ 7, 82, 35, 21, 24, 59, 60 } };
for (int k = 0; k < a.length; k++) { // 直接调⽤数组arrays⾥的sort()这个⽅法对⾥边的⼀维数组进⾏排序 Arrays.sort(a[k]);
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论