您的位置:首页 > 编程语言 > Java开发

传统的数组常规操作(JAVA实现)

2013-04-27 21:56 411 查看
程杰的《大话数据结构》是以C作为演示代码的。

我觉得如何要通HADOOP及其应用,JAVA的数据结构和算法的基础知识也必不可少的。

于是网上找了本电子书《JAVA算法和数据结构》第二版中文版。跟着看一看。

这书也不差哟。

下面的代码是为了引出类的优势,以传统基于过程的算法作比较。

我个人在里面增加了数组排序和元素增加演示。

public class hello {

/**
* @param args
*/
public static void main(String[] args) {
long[] arr;
arr = new long[100];
int nElems = 0;
int j;
int i;
long swap;
long searchKey;
arr[0] = 77;
arr[1] = 99;
arr[2] = 44;
arr[3] = 55;
arr[4] = 22;
arr[5] = 88;
arr[6] = 11;
arr[7] = 00;
arr[8] = 66;
arr[9] = 33;

nElems = 10;

for(j = 0; j < nElems; j++)
System.out.print(arr[j] + " ");
System.out.println("");

searchKey = 66;
for(j = 0; j < nElems; j++)
if(arr[j] == searchKey)
break;
if(j == nElems)
System.out.println("Can't find " + searchKey );
else
System.out.println("Found " + searchKey);

searchKey = 55;
for(j = 0; j < nElems; j++)
if(arr[j] == searchKey)
break;
for(int k = j; k < nElems; k++)
arr[k] = arr[k+1];
nElems--;
System.out.println("Delete " + searchKey);

for(j = 0; j < nElems; j++)
System.out.print(arr[j] + " ");
System.out.println("");

searchKey = 55;
nElems++;
arr[nElems-1] = searchKey;
System.out.println("Add " + searchKey + " to the end;");

for(j = 0; j < nElems; j++)
System.out.print(arr[j] + " ");
System.out.println("");

for(i = 0; i < nElems; i++)
{
for(j = i + 1; j < nElems; j++)
{
if (arr[i] < arr[j])
{
swap = arr[j];
arr[j] = arr[i];
arr[i] = swap;
}
}
}

System.out.println("After sort:");
for(j = 0; j < nElems; j++)
System.out.print(arr[j] + " ");
System.out.println("");
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: