C Program to Sort a random array of n integers using bubble sort algorithm | DS - IProgramX

Q. Sort a random array of n integers (accept the value of n from user) in ascending order by using bubble sort algorithm


Program

#include <stdio.h>
#define MAXSIZE 10

void main()
{
    int array[MAXSIZE];
    int i, j, num, temp;

    printf("Enter the value of num \n");
    scanf("%d", &num);
    printf("Enter the elements one by one \n");
    for (i = 0; i < num; i++)
    {
        scanf("%d", &array[i]);
    }
    printf("Input array is \n");
    for (i = 0; i < num; i++)
    {
        printf("%d\n", array[i]);
    }
    for (i = 0; i < num; i++)
    {
        for (j = 0; j < (num - i - 1); j++)
        {
            if (array[j] > array[j + 1])
            {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }
    printf("Sorted array is...\n");
    for (i = 0; i < num; i++)
    {
        printf("%d\n", array[i]);
    }
}

Output: 

Enter the value of num
4
Enter the elements one by one
3
5
3
8
Input array is
3
5
3
8
Sorted array is...
3
3
5
8

Post a Comment

9 Comments

  1. 2 : create and display data

    import pandas as pd

    data = {
    'RollNo': [1, 2, 3, 4, 5],
    'Name': ['Amit', 'Priya', 'Rahul', 'Sneha', 'Karan'],
    'Maths': [78, 85, 62, 90, 70],
    'Science': [82, 79, 68, 95, 74],
    'English': [75, 88, 71, 84, 69]
    }

    df = pd.DataFrame(data)

    print('Student Marks Dataset:')
    print(df)

    ReplyDelete
  2. 3: analyse st marks using stat


    import pandas as pd

    data = {
    'Name': ['Shardul', 'Ram', 'Rahul', 'Sarthak', 'Krishna',
    'Omkar', 'Karan', 'Zaid', 'Varun', 'Atharv'],
    'Maths': [78, 85, 62, 90, 70, 88, 55, 95, 60, 73],
    'Science': [82, 79, 68, 95, 74, 91, 60, 89, 65, 77],
    'English': [75, 88, 71, 84, 69, 85, 58, 92, 63, 80]
    }

    df = pd.DataFrame(data)

    df['Total'] = df[['Maths', 'Science', 'English']].sum(axis=1)
    df['Average'] = df[['Maths', 'Science', 'English']].mean(axis=1).round(2)

    print('Student Marks Analysis:')
    print(df)

    topper = df.loc[df['Total'].idxmax()]
    lowest = df.loc[df['Total'].idxmin()]

    print('\nHighest Scorer:')
    print('Name:', topper['Name'])
    print('Total Marks:', topper['Total'])

    print('\nLowest Scorer:')
    print('Name:', lowest['Name'])
    print('Total Marks:', lowest['Total'])

    ReplyDelete
  3. 4 : emp salary analysis dept wise


    import pandas as pd

    data = {
    'EmpID': range(1, 11),
    'Name': ['Amit', 'Priya', 'Rahul', 'Sneha', 'Karan',
    'Neha', 'Rohan', 'Isha', 'Vivek', 'Anjali'],
    'Department': ['IT', 'HR', 'IT', 'Finance', 'HR',
    'IT', 'Finance', 'HR', 'IT', 'Finance'],
    'Salary': [55000, 42000, 61000, 48000, 45000,
    58000, 50000, 47000, 63000, 52000]
    }

    df = pd.DataFrame(data)

    print('Employee Salary Dataset:')
    print(df)

    print('\nAverage Salary:', df['Salary'].mean())
    print('Highest Salary:', df['Salary'].max())
    print('Lowest Salary:', df['Salary'].min())

    dept_count = df.groupby('Department')['EmpID'].count()
    print('\nEmployees per Department:')
    print(dept_count)

    ReplyDelete
  4. 5 : csv


    import pandas as pd

    data = {
    'RollNo': [1, 2, 3, 4, 5],
    'Name': ['Aarav', 'Priya', 'Rahul', 'Sneha', 'Aditya'],
    'Marks': [78, 85, 62, 90, 70]
    }

    df = pd.DataFrame(data)

    df.to_csv('students.csv', index=False)

    df = pd.read_csv('students.csv')

    print("Dataset loaded from CSV:")
    print(df)

    print("\nShape of Dataset:")
    print(df.shape)

    print("\nColumn Names:")
    print(list(df.columns))

    ReplyDelete
  5. 6: basic op on dataset using pandas

    import pandas as pd

    data = {
    'RollNo': [1, 2, 3, 4, 5],
    'Name': ['Amit', 'Priya', 'Rahul', 'Sneha', 'Karan'],
    'Marks': [78, 85, 62, 90, 70]
    }

    df = pd.DataFrame(data)

    print('Full Dataset:')
    print(df)

    print('\nFirst 2 Records:')
    print(df.head(2))

    print('\nColumn Names:')
    print(list(df.columns))

    print('\nData Types:')
    print(df.dtypes)

    ReplyDelete
  6. 7 : sql


    import sqlite3

    conn = sqlite3.connect(':memory:')
    cur = conn.cursor()

    cur.execute('''
    CREATE TABLE Student (
    RollNo INTEGER PRIMARY KEY,
    Name TEXT,
    Marks INTEGER
    )
    ''')

    students = [
    (1, 'Amit', 78),
    (2, 'Priya', 85),
    (3, 'Rahul', 62),
    (4, 'Sneha', 90),
    (5, 'Karan', 70)
    ]
    cur.executemany('INSERT INTO Student VALUES (?, ?, ?)', students)
    conn.commit()

    print('All Students:')
    for row in cur.execute('SELECT * FROM Student'):
    print(row)

    print('\nStudents with Marks > 75:')
    for row in cur.execute('SELECT Name, Marks FROM Student WHERE Marks > 75'):
    print(row)

    print('\nStudents ordered by Marks (descending):')
    for row in cur.execute('SELECT Name, Marks FROM Student ORDER BY Marks DESC'):
    print(row)

    conn.close()

    ReplyDelete
  7. 8 : EDA


    import pandas as pd
    import matplotlib.pyplot as plt

    data = {'Marks': [78, 85, 62, 90, 70, 88, 55, 95, 60, 73]}
    df = pd.DataFrame(data)

    print('Mean:', df['Marks'].mean())
    print('Median:', df['Marks'].median())
    print('Mode:', df['Marks'].mode()[0])


    plt.figure()
    plt.hist(df['Marks'], bins=5, edgecolor='black')
    plt.title('Histogram of Marks')
    plt.xlabel('Marks')
    plt.ylabel('Frequency')
    plt.savefig('histogram.png')

    plt.figure()
    plt.boxplot(df['Marks'])
    plt.title('Box Plot of Marks')
    plt.ylabel('Marks')
    plt.savefig('boxplot.png')


    plt.figure()
    plt.scatter(range(1, len(df) + 1), df['Marks'])
    plt.title('Scatter Plot of Marks')
    plt.xlabel('Student Index')
    plt.ylabel('Marks')
    plt.savefig('scatter.png')

    plt.show()

    ReplyDelete
  8. 9 : adv visual, heatmap and pivot table


    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt

    data = {
    'Department': ['IT', 'HR', 'IT', 'Finance', 'HR', 'IT', 'Finance'],
    'Quarter': ['Q1', 'Q1', 'Q2', 'Q1', 'Q2', 'Q1', 'Q2'],
    'Sales': [120, 90, 150, 80, 95, 130, 100]
    }

    df = pd.DataFrame(data)


    pivot = pd.pivot_table(
    df,
    values='Sales',
    index='Department',
    columns='Quarter',
    aggfunc='mean'
    )

    print('Pivot Table:')
    print(pivot)


    plt.figure()
    sns.heatmap(pivot, annot=True, cmap='YlGnBu', fmt='.0f')
    plt.title('Average Sales: Department vs Quarter')
    plt.savefig('heatmap.png')

    plt.show()

    ReplyDelete
  9. 10: case study, real data



    import pandas as pd
    import matplotlib.pyplot as plt

    data = {
    'OrderID': [1001, 1002, 1003, 1004, 1005,
    1006, 1007, 1008, 1009, 1010],

    'Customer': ['Aditi', 'Rahul', 'Sneha', 'Arjun', 'Meera',
    'Karan', 'Priya', 'Rohan', 'Isha', 'Devika'],

    'Product': ['Laptop', 'Phone', 'Headphones', 'Laptop',
    'Tablet', 'Phone', 'Monitor', 'Printer',
    'Phone', 'Laptop'],

    'Region': ['West', 'North', 'South', 'West', 'East',
    'South', 'North', 'East', 'West', 'South'],

    'Sales': [55000, 18000, 2500, 62000, 22000,
    16000, 12000, 9000, 20000, 58000],

    'Profit': [6000, 2500, 500, 7000, 2800,
    1800, 1500, 900, 2700, 6500]
    }

    df = pd.DataFrame(data)

    df.to_csv('sales_data.csv', index=False)

    df = pd.read_csv('sales_data.csv')


    print("Dataset Shape:")
    print(df.shape)

    print("\nDataset Information:")
    df.info()

    print("\nFirst Five Records:")
    print(df.head())


    df = df.drop_duplicates()

    df = df.dropna(subset=['Sales', 'Profit'])


    print("\nDescriptive Statistics:")
    print(df[['Sales', 'Profit']].describe())


    region_sales = df.groupby('Region')['Sales'].sum()

    region_sales = region_sales.sort_values(ascending=False)

    print("\nSales by Region:")
    print(region_sales)



    plt.figure(figsize=(8, 5))

    region_sales.plot(kind='bar')

    plt.title("Total Sales by Region")
    plt.xlabel("Region")
    plt.ylabel("Total Sales")

    plt.xticks(rotation=0)

    plt.savefig('region_sales.png')

    plt.show()

    ReplyDelete