洛谷P1177【模板】排序:十種排序算法全解(1)

扯談

之前我已經把十大排序算法全講了一遍(具體詳見專欄C++排序算法),今天我們來用一道簡單的題目總結實戰一下。


算法實現

一、桶排序(Bucket Sort)

?適用場景?:數據范圍已知且較小(需根據測試數據調整偏移量)

// Java
import java.io.*;
public class Main {static final int OFFSET = 100000;public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int n = Integer.parseInt(br.readLine());int[] cnt = new int[200001];String[] strs = br.readLine().split(" ");for (int i = 0; i < n; i++) cnt[Integer.parseInt(strs[i]) + OFFSET]++;StringBuilder sb = new StringBuilder();for (int i = 0; i <= 200000; i++) while (cnt[i]-- > 0) sb.append(i - OFFSET).append(" ");System.out.println(sb);}
}
# Python
n = int(input())
nums = list(map(int, input().split()))
offset = 10**5
cnt = [0] * (2*10**5 +1)
for num in nums:cnt[num + offset] +=1
res = []
for i in range(len(cnt)):while cnt[i] >0:res.append(str(i - offset))cnt[i] -=1
print(' '.join(res))
// C
#include <stdio.h>
#define OFFSET 100000
int cnt[200001];
int main() {int n, x;scanf("%d", &n);for(int i=0; i<n; ++i) {scanf("%d", &x);cnt[x + OFFSET]++;}for(int i=0; i<=200000; ++i)while(cnt[i]--) printf("%d ", i - OFFSET);return 0;
}
// C++
#include <iostream>
using namespace std;
const int OFFSET = 1e5;
int cnt[200001];
int main() {ios::sync_with_stdio(false);int n, x;cin >> n;for(int i=0; i<n; ++i) {cin >> x;cnt[x + OFFSET]++;}for(int i=0; i<=200000; ++i)while(cnt[i]--) cout << i - OFFSET << " ";return 0;
}

二、基數排序(Radix Sort)

?支持正負數處理?

// Java
import java.io.*;
public class Main {static final int RADIX = 10;public static void main(String[] args) throws IOException {BufferedReader br = new BufferedReader(new InputStreamReader(System.in));int n = Integer.parseInt(br.readLine());String[] strs = br.readLine().split(" ");int[] arr = new int[n];for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(strs[i]);// 分離正負數int posCount = 0;for (int num : arr) if (num >= 0) posCount++;int[] negs = new int[n - posCount];int[] poss = new int[posCount];int ni = 0, pi = 0;for (int num : arr) {if (num < 0) negs[ni++] = -num;else poss[pi++] = num;}// 排序負數if (negs.length > 0) radixSort(negs);// 排序正數if (poss.length > 0) radixSort(poss);// 合并結果StringBuilder sb = new StringBuilder();for (int i = negs.length - 1; i >= 0; i--) sb.append(-negs[i]).append(" ");for (int num : poss) sb.append(num).append(" ");System.out.println(sb);}static void radixSort(int[] arr) {int max = 0;for (int num : arr) if (num > max) max = num;for (exp = 1; max / exp > 0; exp *= 10) countingSort(arr, exp);}static void countingSort(int[] arr, int exp) {int[] output = new int[arr.length];int[] count = new int[RADIX];for (int num : arr) count[(num / exp) % RADIX]++;for (int i = 1; i < RADIX; i++) count[i] += count[i - 1];for (int i = arr.length - 1; i >= 0; i--) {int digit = (arr[i] / exp) % RADIX;output[--count[digit]] = arr[i];}System.arraycopy(output, 0, arr, 0, arr.length);}
}
# Python
def radix_sort(arr):if not arr:return []max_num = max(map(abs, arr))exp = 1while max_num // exp > 0:counting_sort(arr, exp)exp *= 10return arrdef counting_sort(arr, exp):output = [0] * len(arr)count = [0] * 19  # 處理負數偏移for num in arr:index = (num // exp) % 10 + 9count[index] += 1for i in range(1, 19):count[i] += count[i - 1]for i in range(len(arr)-1, -1, -1):index = (arr[i] // exp) % 10 + 9output[count[index]-1] = arr[i]count[index] -= 1arr[:] = outputn = int(input())
arr = list(map(int, input().split()))
neg = [x for x in arr if x < 0]
pos = [x for x in arr if x >= 0]
radix_sort(neg)
radix_sort(pos)
neg = [-x for x in reversed(neg)]
print(' '.join(map(str, neg + pos)))
// C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define RADIX 10void counting_sort(int arr[], int n, int exp) {int* output = (int*)malloc(n * sizeof(int));int count[19] = {0}; // 處理負數偏移for (int i = 0; i < n; i++) {int digit = (arr[i] / exp) % RADIX + 9;count[digit]++;}for (int i = 1; i < 19; i++) count[i] += count[i-1];for (int i = n-1; i >= 0; i--) {int digit = (arr[i] / exp) % RADIX + 9;output[--count[digit]] = arr[i];}memcpy(arr, output, n * sizeof(int));free(output);
}void radix_sort(int arr[], int n) {if (n == 0) return;int max_val = 0;for (int i = 0; i < n; i++) {int abs_val = abs(arr[i]);if (abs_val > max_val) max_val = abs_val;}for (int exp = 1; max_val/exp > 0; exp *= 10)counting_sort(arr, n, exp);
}int main() {int n;scanf("%d", &n);int* arr = malloc(n * sizeof(int));for (int i = 0; i < n; i++) scanf("%d", &arr[i]);// 分離正負數int neg_count = 0;for (int i = 0; i < n; i++) if (arr[i] < 0) neg_count++;int* negs = malloc(neg_count * sizeof(int));int* poss = malloc((n - neg_count) * sizeof(int));int ni = 0, pi = 0;for (int i = 0; i < n; i++) {if (arr[i] < 0) negs[ni++] = -arr[i];else poss[pi++] = arr[i];}radix_sort(negs, neg_count);radix_sort(poss, n - neg_count);// 合并結果for (int i = neg_count-1; i >= 0; i--) printf("%d ", -negs[i]);for (int i = 0; i < n - neg_count; i++) printf("%d ", poss[i]);return 0;
}
// C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;void counting_sort(vector<int>& arr, int exp) {vector<int> output(arr.size());int count[19] = {0}; // 負數偏移處理for (int num : arr) count[(num / exp) % 10 + 9]++;for (int i = 1; i < 19; i++) count[i] += count[i-1];for (int i = arr.size()-1; i >= 0; i--) {int digit = (arr[i] / exp) % 10 + 9;output[--count[digit]] = arr[i];}arr = output;
}void radix_sort(vector<int>& arr) {if (arr.empty()) return;int max_val = 0;for (int num : arr) max_val = max(max_val, abs(num));for (int exp = 1; max_val/exp > 0; exp *= 10)counting_sort(arr, exp);
}int main() {ios::sync_with_stdio(false);int n; cin >> n;vector<int> arr(n), negs, poss;for (int i = 0; i < n; i++) {cin >> arr[i];if (arr[i] < 0) negs.push_back(-arr[i]);else poss.push_back(arr[i]);}radix_sort(negs);radix_sort(poss);reverse(negs.begin(), negs.end());for (int num : negs) cout << -num << " ";for (int num : poss) cout << num << " ";return 0;
}

由于篇幅限制,剩余請詳見洛谷P1177【模板】排序:十種排序算法全解(2),求關

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/902100.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/902100.shtml
英文地址,請注明出處:http://en.pswp.cn/news/902100.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

SuperMap iClient3D for WebGL 如何加載WMTS服務

在 SuperMap iClient3D for WebGL 中加載WMTS服務時&#xff0c;參數配置很關鍵&#xff01;下面我們詳細介紹如何正確填寫參數&#xff0c;確保影像服務完美加載。 一、數據制作 對于上述視頻中的地圖制作&#xff0c;此處不做講述&#xff0c;如有需要可訪問&#xff1a;Onl…

再讀bert(Bidirectional Encoder Representations from Transformers)

再讀 BERT&#xff0c;仿佛在數字叢林中邂逅一位古老而智慧的先知。初次相見時&#xff0c;驚嘆于它以 Transformer 架構為羅盤&#xff0c;在預訓練與微調的星河中精準導航&#xff0c;打破 NLP 領域長久以來的迷霧。而如今&#xff0c;書頁間躍動的不再僅是 Attention 機制精…

從零開始 保姆級教程 Ubuntu20.04系統安裝MySQL8、服務器配置MySQL主從復制、本地navicat遠程連接服務器數據庫

從零開始&#xff1a;Ubuntu 20.04 系統安裝 MySQL 8、服務器配置 MySQL 主從復制、本地 Navicat 遠程連接服務器數據庫 初始化服務器1. 更新本地軟件包列表2. 安裝 MySQL 服務器3. 查看 MySQL 安裝版本4. 登錄 MySQL 管理終端5. 設置 root 用戶密碼&#xff08;推薦使用 nativ…

java怎么完善注冊,如果郵箱中途更換,能否判斷

解析在下面 附贈代碼 private static class CodeInfo {String code;long timestamp;CodeInfo(String code, long timestamp) {this.code code;this.timestamp timestamp;}}// 存儲驗證碼&#xff08;郵箱 -> 驗證碼信息&#xff09;(保證線程安全) 以免中途更改郵箱pri…

n8n 中文系列教程_01. 簡單易懂的現代AI魔法,n8n的快速了解與概念科普(文末有彩蛋)

1. 教程簡介 歡迎來到“無代碼工具探索”課程&#xff0c;這是專為非技術人員設計的指南&#xff08;當然&#xff0c;技術人員也可以從中受益&#xff09;。我們的目標是通過無代碼工具來提升工作效率&#xff0c;尤其是利用像 n8n 這樣的靈活數據庫平臺。這些工具被譽為“現…

解碼 Web Service:從技術原理到應用場景的深度剖析

Web Service 是一種基于網絡的、分布式的計算技術&#xff0c;它允許不同的應用程序之間通過網絡進行通信和交互。以下是關于 Web Service 的詳細介紹&#xff1a; 一、定義與概念 Web Service 是一種可以通過 Web 協議&#xff08;如 HTTP&#xff09;進行訪問的軟件組件&am…

Nacos啟動報錯

Nacos啟動是在單機模式下&#xff0c;不是集群模式 點擊startup.cmd啟動會報錯 打開bin目錄 rem是注釋的意思&#xff0c;在nacos1.3.2之后&#xff0c;nacos默認的都是集群模式&#xff0c;我們這里單機測試就是用單機模式。 也可以修改MODE&#xff0c;如果選擇不修改&…

uniapp-商城-26-vuex 使用流程

為了能在所有的頁面都實現狀態管理&#xff0c;我們按照前面講的頁面進行狀態獲取&#xff0c;然后再進行頁面設置和布局&#xff0c;那就是重復工作&#xff0c;vuex 就會解決這樣的問題&#xff0c;如同類、高度提煉的接口來幫助我們實現這些重復工作的管理。避免一直在造一樣…

Git 命令速查手冊

聽說用美圖可以釣讀者&#xff1f; 一、基礎操作核心命令 1. 倉庫初始化與克隆 命令作用示例git init創建新倉庫git init my-projectgit clone克隆遠程倉庫git clone [https://github.com/user/repo.git](https://github.com/user/repo.git)git remote add關聯遠程倉庫git re…

信息量、香農熵、交叉熵、KL散度總結

信息量 對于一個事件而言&#xff0c;它一般具有三個特征&#xff1a; 小概率事件往往具有較大的信息量 大概率事件往往具有較小的信息量 獨立事件的信息量相互可以相加 比如我們在買彩票這個事件中&#xff0c;彩票未中獎的概率往往很高&#xff0c;對我們而言一點也不稀…

使用C語言的cJSON中給JSON字符串添加轉義

在 cJSON 庫中&#xff0c;沒有直接提供 一個函數來專門給 JSON 字符串添加轉義&#xff08;如將 " 轉義為 \"&#xff0c;\n 轉義為 \\n 等&#xff09;。 但 cJSON 在 序列化&#xff08;cJSON_Print 或 cJSON_PrintUnformatted&#xff09; 時會自動處理轉義字符…

宇樹機器狗go2—slam建圖(1)點云格式

0.前言 上一篇番外文章教大家如何在宇樹機器狗go2的gazebo仿真環境中實現簡單的導航運動&#xff0c;本期文章會教大家如何讓宇樹的機器狗go2在仿真環境中進行slam建圖時經常會遇到的一些點云格式&#xff0c;在后續的slam建圖和slam算法解析的時候會經常與這些點云信息打交道…

linux socket編程之udp(實現客戶端和服務端消息的發送和接收)

目錄 一.創建socket套接字(服務器端) 二.bind將prot與端口號進行綁定(服務器端) 2.1填充sockaddr_in結構 2.2bind綁定端口 三.直接通信(服務器端) 3.1接收客戶端發送的消息 3.2給客戶端發送消息 四.客戶端通信 4.1創建socket套接字 4.2客戶端bind問題 4.3直接通信即可…

第1期:Python基礎語法入門

1.1 Python簡介 Python是一種解釋型、面向對象、動態數據類型的高級編程語言。它設計簡潔&#xff0c;易于學習&#xff0c;適合初學者。Python廣泛應用于數據科學、人工智能、Web開發、自動化腳本等領域。它的語法簡潔易懂&#xff0c;強調代碼的可讀性。 1.2 安裝Python與配…

使用EXCEL繪制平滑曲線

播主播主&#xff0c;你都多少天沒更新了&#xff01;&#xff01;&#xff01;泥在干什么&#xff1f;你還做這個賬號麻&#xff1f;&#xff01;&#xff01;&#xff01; 做的做的&#xff08;哭唧唧&#xff09;&#xff0c;就是最近有些忙&#xff0c;以及…… 前言&…

當算力遇上馬拉松:一場科技與肉身的極限碰撞

目錄 一、從"肉身苦修"到"科技修仙" 二、馬拉松的"新大陸戰爭" 三、肉身會被算法"優化"嗎? 馬拉松的下一站是"人機共生"時代 當AI能預測你的馬拉松成績,算法能規劃最佳補給方案,智能裝備讓訓練效率翻倍——你還會用傳…

MLLMs for TSAD ?

項目鏈接:Multimodal LLMs Advance Time Series Analysis 代碼鏈接:https://github.com/mllm-ts/VisualTimeAnomaly 出處:ICLR 2025 一 文章動機 多模態 LLM (MLLM) 通過 “視覺” 方式處理時序的潛力仍未充分探索; 人類檢測 “時序異常” 的自然方式:可視化、文本描…

開發基于python的商品推薦系統,前端框架和后端框架的選擇比較

開發一個基于Python的商品推薦系統時&#xff0c;前端和后端框架的選擇需要綜合考慮項目需求、開發效率、團隊熟悉度以及系統的可擴展性等因素。 以下是一些推薦的框架和建議&#xff1a; 后端框架 Flask 優點&#xff1a; 輕量級&#xff1a;Flask的核心非常簡潔&#xff0c;…

chili3d調試筆記2+添加web ui按鈕

onclick 查找 打個斷點看看 挺可疑的&#xff0c;打個斷點看看 挺可疑的&#xff0c;打個斷點看看 打到事件監聽上了 加ui了 加入成功 新建彈窗-------------------------------------- 可以模仿這個文件&#xff0c;寫彈窗 然后在這里注冊一下&#xff0c;外部就能調用了 對了…

【重學Android】1.關于@Composer注解的一點知識筆記

最新因為一些原因&#xff0c;開始重新學習Android及kotlin編程&#xff0c;也覺得可以順帶記錄下這個過程中的一些知識點&#xff0c;也可以用作日后自己查找復習。 Composable 注解在 Android 開發中的使用 Composable 是 Jetpack Compose&#xff08;Android 的現代聲明式…