Bubble Sort: Imperative vs Funtional Way

Imperative Way (Optimized)

public void bubbleSort(int[] a, int n) {
  if (n <= 1) return
  // execute n times
  for (int i = 0; i < n; i++) {
    boolean everyElementSmallerThanNextOne = true;
    int k = i + 1; // times
    int kthLargePosition = n - i - 1;
    for (int j = 0; j < kthLargePosition; j++) {
        if (a[j] > a[j + 1]) {
            int tmp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = tmp;
            everyElementSmallerThanNextOne = false;
        }
    }
    if (everyElementSmallerThanNextOne) break;
  }
}

Functional Way (Not Optimized Yet)

bubbleToTop (x:y:remains)
  | x > y = y : (bubbleToTop x : remains)
  | otherwise =  x : (bubbleToTop y : remains)
bubbleToTop (emptyOrSingleElement) = (emptyOrSingleElement)

bubble (list times)
  | times == (length list) = list
  | otherwise = bubble (bubbleToTop list) times + 1

bubbleSort list = bubble list 0

Functional Way (Optimized)

bubbleSort list = bubble list round_swap_happened=false 0
bubble (list round_swap_happened times)
  | round_swap_happened == false = list
  | times == (length list) = list
  -- | every new round, the swap flage should be reset to false
  | otherwise = bubble (bubbleToTop list round_swap_happened=false) times + 1

bubbleToTop (x:y:remains round_swap_happened)
  -- | when it happens, update the flag
  | x > y = y : (bubbleToTop x : remains round_swap_happened=true)
  | otherwise =  x : (bubbleToTop y : remains round_swap_happened)
bubbleToTop (emptyOrSingleElement) = (emptyOrSingleElement round_swap_happened) 
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,181评论 0 10
  • 1 总是以自己的角度考虑问题,会失去很多重要的机会。 2 不盲从是一种生活态度。 3 认定了,就不要放弃,不管是来...
    大Coco的中文叫韩大脸阅读 1,589评论 0 1
  • 对于单休的我来说,周日是我的解放日,可以任性可以放松,偶尔有一觉睡到第二天中午的美容觉,偶尔约会老相识聊聊小学同学...
    小古月小古月阅读 2,761评论 0 1
  • UILable summary UILabel的常见属性 UIFont类 Method Demo
    MarkTang阅读 2,688评论 0 2
  • 上了年纪的老人,手头或多或少都有些老物件,我的父母也不例外。 也许是节俭一辈子的缘故吧,父母特喜欢攒“...
    梅子浠阅读 1,369评论 0 2

友情链接更多精彩内容