java 排序!

来源:互联网 发布:python cms 管理系统 编辑:程序博客网 时间:2024/06/14 05:02

 /**
 * 26个英文字母的排序。
 * @author rui
 *
 */
class  CharSort
{
 public static void main(String[] args)
 {
  for (char i = 'a'; i <='z'; i++)
  {
   System.out.print(i+"  ");
  }
 }
}

/**
 * 数组取值,查找。【直接查找方法】
 *
 * @author rui
 *
 */
public class ArrayValue
{
 public static int serch(int[] in, int temp)
 {
  for (int i = 0; i < in.length; i++)
  {
   if (temp == in[i])
   {
    System.out.println(i);
    return i; // 添加此语句,则返回和目标结果相等的第一次出现的索引位置。
   }
  }
  return -1;
 }

 public static void main(String[] args)
 {
  int[] a =
  { 1, 4, 6, 2, 3, 4 };
  ArrayValue.serch(a, 4);
 }
}

/**
 * 二分查找法。数组必须是有序的,才能快速查找。
 */
class ArraySort
{
 public static int sort(int[] a, int temp)
 {
  int start = 0;
  int high = a.length - 1;
  int middle;
  while (start <= high)
  {
   middle = (start + high) / 2;
   for (int i = 0; i < a.length; i++)
   {
    System.out.print(a[i]);
    if (i == middle)
    {
     System.out.print("  " + "中间位置:" + middle + "   ");
    }
    System.out.print(" ");
   }
   System.out.println();
   if (temp == a[middle])
   {
    return middle;
   }
   if (temp < a[middle])
   {
    high = middle - 1;
   }
   if (temp > a[middle])
   {
    start = middle + 1;
   }
  }
  return -1;
 }

 public static void main(String[] args)
 {
  int[] a ={ 3, 5, 7, 9, 12, 14, 15, 19, 26 };
  int index = ArraySort.sort(a, 3);
  System.out.println(index);
 }
}

/**
 * 冒泡排序,查找。
 *
 * @author rui
 *
 */
class SortTestMy
{
 public static void sort(int[] i)
 {
  int temp;
  for (int j = 0; j < i.length - 1; j++)
  {
   for (int j2 = 0; j2 < i.length - j - 1; j2++)
   {
    if (i[j2] > i[j2 + 1])
    {

     temp = i[j2];
     i[j2] = i[j2 + 1];
     i[j2 + 1] = temp;
    }
   }
  }
  for (int k = 0; k < i.length; k++)
  {
   System.out.println(i[k]);
  }

 }
}

以上为基本的几种排序,及其查找的方法。