陣列的操作處理與陣列元素的氣泡排序 (轉)

worldblog發表於2007-12-14
陣列的操作處理與陣列元素的氣泡排序 (轉)[@more@]

//(1)查詢陣列元素

static void Main(string[] args)
{
  // TODO: 查詢陣列元素
  int[] a= new int[100];
  Console.WriteLine("輸入數字");
  string s=Console.ReadLine();

  int x=Int32.Parse(s);
  Console.WriteLine("n 輸入int陣列元素 n");

  for(int i=0;i  {
  string s1=Console.ReadLine();
  a[i]=Int32.Parse(s1);
  }

  Console.WriteLine("搜查元素n");
  string s3=Console.ReadLine();
  int x2=Int32.Parse(s3);
  //迴圈部分陣列
  for(int i=0;i  {
  if(a[i]==x2)
  {
 Console.WriteLine("Search succesul");
 Console.WriteLine("Element {0} found at location {1}n",x2,i+1);
  Console.ReadLine ();
 return;
  }
  }
}
---------------------------------------
//(2)查詢陣列元素中最大和最小的元素


static void Main(string[] args)
{
  // TODO: 找出最大和最小的元素
  int n;
  float large,small;
  int[] a = new int[50];
  Console.WriteLine("輸入int陣列大小");
  string s= Console.ReadLine();
  n=Int32.Parse(s);
  Console.WriteLine("輸入陣列元素");
  for(int i=0;i  {
 string s1=Console.ReadLine();
 a[i]=Int32.Parse(s1);
  }
  large =a[0];
  small= a[0];
  for(int i=1;i  {
 if(a[i]>large)
 large=a[i]; //large變數
 else if(a[i] small=a[i]; //更新small變數
  }
  Console.WriteLine("Largest element in the array is {0}",large);
  Console.WriteLine("Smallest element in the array is {0}",small);
  Console.ReadLine ();//暫停
}


----------------------------------------------
//陣列元素的氣泡排序

/*
第一遍使最輕的記錄上升到陣列的最頂端,
第二遍使剩下的最小的上升到第二位置,
第二遍掃描時不必再比較最頂端的記錄
*/

static void Main(string[] args)
{
  int[] a= new int[100];
  Console.WriteLine("輸入int陣列裡的元素數目");
  string s=Console.ReadLine();
  int x=Int32.Parse(s);

  Console.WriteLine("輸入元素");
  for(int j=0;j  {
 string s1=Console.ReadLine();
 a[j]=Int32.Parse(s1);
  }

  int limit= x-1;
  for(int pass=0;pass  {
 for(int j=0;j {
  if(a[j]>a[j+1])
  {
  int k=a[j]; //陣列元素
  a[j]=a[j+1]; //陣列元素交換
  a[j+1]=k; //陣列元素交換
  }
 }
  }

  Console.WriteLine("Sorted elements of an array are(氣泡排序)");

  for (int j=0;j  {
  Console.WriteLine(a[j]);
  }
  Console.ReadLine ();
}

---------------------------------------


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10752043/viewspace-993433/,如需轉載,請註明出處,否則將追究法律責任。

相關文章