冒泡排序法

来源:互联网 发布:微信机器人源码 编辑:程序博客网 时间:2024/05/21 19:44

public class Sortor {
 

 /**
  * 使用冒泡排序法,将整数型的泛型集合中的整数,按照从小到大重新排序
  * @param list 要重新排序的整数型泛型集合
  */
 public static void sortByAsc(List<Integer> list) throws Exception
 {
  
  Integer temp = null;
  for (int i = 0; i < list.size(); i++)
  {
   for (int j = 0; j < list.size() - i - 1; j++)
   {
    if (list.get(j) > list.get(j + 1))
    {
     temp = list.get(j);
     list.set(j, list.get(j + 1));
     list.set(j + 1, temp);
    }
   }
  }
  
 }
 
 
 
 /**
  * 将整数组合成的字符串升序排列
  * @param s 要升序排列的字符串
  * @param separator 字符串中各个整数之间的分隔符
  * @throws Exception
  */
 public static String sortByAsc(String s, String separator) throws Exception
 {
  
  String[] ss = s.split(separator);
  
  for (int i = 0; i < ss.length; i++)
  {
   for (int j = 0; j < ss.length - i - 1; j++)
   {
    int a = Integer.parseInt(ss[j]);
    int b = Integer.parseInt(ss[j + 1]);
    if (a > b)
    {
     a = a ^ b;
     b = a ^ b;
     a = a ^ b;
    }
    ss[j] = String.valueOf(a);
    ss[j + 1] = String.valueOf(b);
   }
  }
  
  StringBuffer result = new StringBuffer(ss[0]);
  for (int i = 1; i < ss.length; i++)
  {
   result.append(separator + ss[i]);
  }
  
  return result.toString();
  
 }
 
 /**
  * 将整数组合成的字符串升序排列并保持数字格式(例如字符串中有一个02的数,排序后要保持02的格式,不能变成2)
  * @param s 要升序排列的字符串
  * @param separator 字符串中各个整数之间的分隔符
  * @return
  */
 public static String sortByAscAndStandFormatOfNumeber(String s, String separator)
 {
  
  String[] source = s.split(separator);//这个数组为源数组,不变化。最后将根据与ss一起进行冒泡排序的is中的序列号变化后顺序从这个数组中取元素
  String[] ss = s.split(separator);//用于排序的数组
  
  Integer[] is = new Integer[ss.length];//记录ss中各个元素的序列号,冒泡排序法中调换位置仅仅是针对is
  for (int i = 0; i < is.length; i++)
  {
   is[i] = i;
  }
  
  for (int i = 0; i < ss.length; i++)
  {
   for (int j = 0; j < ss.length - i - 1; j++)
   {
    int a = Integer.parseInt(ss[j]);
    int b = Integer.parseInt(ss[j + 1]);
    int c = is[j];
    int d = is[j + 1];
    if (a > b)
    {
     a = a ^ b;
     b = a ^ b;
     a = a ^ b;
     
     c = c ^ d;
     d = c ^ d;
     c = c ^ d;
    }
    ss[j] = String.valueOf(a);
    ss[j + 1] = String.valueOf(b);
    is[j] = c;
    is[j + 1] = d;
   }
  }
  
  StringBuffer result = new StringBuffer(source[is[0]]);
  for (int i = 1; i < source.length; i++)
  {
   result.append(separator + source[is[i]]);
  }
  
  return result.toString();
  
 }

 
 

  
 }