php面试题--并列排名问题

  给定一个二维数组:

    

php
    $data = [
                ['name' =>'j1', 'score' => '80'],
                ['name' =>'j2', 'score' => '90'],
                ['name' =>'j3', 'score' => '50'],
                ['name' =>'j4', 'score' => '70'],
                ['name' =>'j5', 'score' => '95'],
                ['name' =>'j6', 'score' => '100'],
                ['name' =>'j7', 'score' => '60'],
                ['name' =>'j8', 'score' => '50'],
          ['name' =>'j9', 'score' => '80'],
]; ?>

最后的结果为:

[
    ['name' => 'j6', 'score' => '100', 'deep' => 1],
    ['name' => 'j5', 'score' => '95', 'deep' => 2],
    ['name' => 'j2', 'score' => '90', 'deep' => 3],
    ['name' => 'j1', 'score' => '80', 'deep' => 4],
['name' => 'j9', 'score' => '80', 'deep' => 4], ['name' => 'j4', 'score' => '70', 'deep' => 5], ['name' => 'j7', 'score' => '60', 'deep' => 6], ['name' => 'j3', 'score' => '50', 'deep' => 7], ['name' => 'j8', 'score' => '50', 'deep' => 7] ]

要求所有关于排序的操作都不能使用php自带的系统函数,必须自己写排序算法(冒泡、插入、选择、快排.....),时间20分钟

 

2018年都过了27天了,总结下自己2017年的面试经历吧。这是上次面试遇到的编程问题,与大家分享自己的处理方法:

先排序用的是选择排序(其实面试那天用的是冒泡算法,当时做完没法拷贝,现在是我第一家公司做的某个项目写的,最后程序可能结果不对,但是我的思路就是先排序在排名,人比较懒,也不想再去写那个冒泡了,实际开发中我都是用的是php自带的系统函数处理的有一个很牛逼的排序函数uasort(),还支持callback,案列地址:http://www.jb51.net/article/71654.htm)

        for($i=0;$i<count($barr)-1;$i++){
                $minIndex = $i;   //自己假定是最大的
                for($j=$i+1;$j<count($barr);$j++){
                    if($barr[$minIndex]['num'] < $barr[$j]['num']){//如果这个值比最大的还大
                       $minIndex = $j;                       
                    }
                }
                if($minIndex != $i){
                    $temp = $barr[$minIndex];
                    $barr[$minIndex] = $barr[$i];
                    $barr[$i] = $temp;                
                }
                
        }

 排名:原理就是循环数组,追加deep值,由于是按照从高到低的顺序排列的,那么第一个就是第一名,当相邻两个数字一样deep就不加否则就加+1

$p = 1;
foreach ($barr as $k => $v) {
               if ($k==0) {
                    $barr[$k]'deep'] = 1;
                } else {
                     if($barr[$k-1]['score']==$arr[$k]['score'])
                          $barr[$k]['deep']=$p;
                }else{
                          $barr[$k]['deep']=++$p;
                }
}

 

你可能感兴趣的:(php面试题--并列排名问题)