排序算法的稳定性(Stability)和原地算法(In-place Algorithm)

稳定性简介:

定义: 如果相等的2个元素,在排序前后的相对位置保持不变,那么这是稳定的排序算法。


举例1:

排序前:5,1,3a,4,7,3b
稳定的排序:1,3a,3b,4,5,7

不稳定的排序: 1,3b,3a,4,5,7

相对位置保持不变。

举例2:

韩梅梅:100分

李华:100分

李强:90分

排序后韩梅梅始终在李华之前。

韩梅梅和李华的相对位置没有改变。


冒泡排序的稳定性

是一个稳定的排序算法。

前面的数据比后面的数据大,才会进行交换,例如:1,2,3,3,4。3和3不会交换。

public class Main {
    public static void main(String[] args) {
        //冒泡排序
        int[] array = {16, 12, 17, 89, 72, 67, 1};
        for(int end = array.length - 1;end > 0; end--){
            boolean sorted = true;
            for (int i = 1; i <= end ; i++) {
             
                    int temp = array[i];
                    array[i] = array[i - 1];
                    array[i-1] = temp;
                    sorted =false;
                }
            }
            if(sorted) break;
        }
        for(int i = 0; i < array.length; i++){
            System.out.print(array[i] + "_");
        }

    }
}

稳定的排序算法也会变成不稳定的排序算法

   if (array[i] < array[i - 1]) {}

交换元素时<写为<= 


原地算法:不依赖额外的资源或者依赖少数的额外资源,仅依靠输出来覆盖输入

空间复杂度为O(1)的都可以认为是原地算法
非原地算法,称为Not-in-place或者Out-of-place
冒泡排序属于ln-place

           for (int i = 1; i <= end ; i++) {
                    int temp = array[i];
                    array[i] = array[i - 1];
                    array[i-1] = temp;
                    sorted =false;
                }

没有依赖额外的资源,是直接对输入的修改。

### 托盘装载货物堆叠优化算法 #### 数据结构算法设计 为了有效解决托盘装载货物的堆叠问题,通常会涉及到多个因素,包括但不限于货物尺寸、重量分布以及稳定性等。一种常见的解决方案是采用三维装箱问题(3D Bin Packing Problem, 3DBPP)模型[^2]。 对于具体的数据结构而言: - **货物对象**:每个货物可以用一个类表示,其中包含属性如长度(length),宽度(width),高度(height),重量(weight),重心位置(center_of_mass)- **托盘容器**:定义为具有固定大小的空间区域,同样具备长宽高三个维度,并且能够容纳一定数量类型的物品。 针对上述提到的数学建模中的托盘最优化摆放解法,这里介绍几种常用的算法技术来实现高效的货物堆放策略: 1. **遗传算法 (Genetic Algorithm)**: 遗传算法是一种模拟自然选择过程的人工智能技术,适用于求解复杂的组合优化问题。在这个场景下,可以通过编码不同的排列方式作为染色体个体,经过多次迭代进化选出最优方案。 2. **分支限界法 (Branch and Bound)**: 这种方法通过对所有可能的情况进行全面搜索并剪枝不可能达到更优解的状态节点,从而找到全局最佳解。虽然理论上能获得精确的结果,但在实际应用中可能会因为计算量过大而难以接受。 3. **启发式规则 (Heuristic Rules)**: 基于经验总结出的一些简单易行的原则指导货物放置顺序,比如先放重物后轻物;优先考虑体积较大的物件;确保每层之间的平衡性等等。这类方法容易实施而且效率较高,但不一定能得到绝对意义上的最好答案。 4. **动态规划 (Dynamic Programming)**: 动态规划适合处理那些存在重复子问题特性的难题。当面对大量相似的小规模实例时,可以预先存储中间结果用于后续快速查询,以此提高整体运算速度。 考虑到现实世界里的物理约束条件,还需要特别注意以下几点: - 物品间的相互作用力(摩擦系数) - 整个堆栈的最大承重限度 - 单位面积内的压力限制 - 安全性便捷性考量 ```python class CargoItem: def __init__(self, length, width, height, weight): self.length = length self.width = width self.height = height self.weight = weight def heuristic_packing_algorithm(pallet_dimensions, cargo_list): """ A simple heuristic algorithm to pack items onto a pallet. Args: pallet_dimensions (tuple): The dimensions of the pallet as (length, width, height). cargo_list (list[CargoItem]): List of cargo items to be packed. Returns: list[list[tuple]]: Layers of packed items represented by their positions on the pallet. """ layers = [] current_layer_items = [] for item in sorted(cargo_list, key=lambda x: (-x.length * x.width * x.height)): placed_successfully = False # Try placing this item at different locations within the layer for pos_x in range(int((pallet_dimensions[0]-item.length)/step_size)+1): for pos_y in range(int((pallet_dimensions[1]-item.width)/step_size)+1): if check_if_position_is_valid(current_layer_items, pos_x*step_size, pos_y*step_size, item): place_item_at(current_layer_items, pos_x*step_size, pos_y*step_size, item) placed_successfully = True break if placed_successfully: break if not placed_successfully: # Start new layer with remaining unpacked items layers.append(current_layer_items.copy()) current_layer_items.clear() # Place the current item into the next layer directly since it couldn't fit elsewhere place_item_at(current_layer_items, 0, 0, item) return layers + [current_layer_items] def check_if_position_is_valid(layer_items, x, y, item_to_place): """Check whether an item can safely occupy space without overlapping others.""" pass # Implementation depends on specific requirements regarding stability etc. def place_item_at(layer_items, x, y, item): """Place an item at specified coordinates inside one layer.""" pass # Actual implementation will depend upon how you represent each layer's contents ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值